使用 Nest.js 和基本 Controller :
import { Body, Controller, Delete, Get, Param, Post, Put, Query } from '@nestjs/common';
import { Hero } from '../entities/hero.entity';
import { HeroService } from './hero.service';
@Controller('hero')
export class HeroController {
constructor(private readonly heroesService: HeroService) {}
@Get()
async get(@Query() query): Promise<Hero[]> {
return await this.heroesService.find(query);
}
@Get(':id')
async getById(@Param('id') id): Promise<Hero> {
return await this.heroesService.findById(id);
}
@Post()
async add(@Body() hero: Hero): Promise<Hero> {
return await this.heroesService.save(hero);
}
//TODO: doesn't seem to work, never called (request 404)
@Put(':id')
async update(@Param('id') id, @Body() hero): Promise<Hero> {
console.log('hey');
return await this.heroesService.update(id, hero);
}
//TODO: doesn't seem to work, never called (request 404)
@Delete('/delete/:id')
async remove(@Param('id') id): Promise<Hero> {
console.log('hey');
return await this.heroesService.remove(id);
}
}
遵循 Nest.js 的基本文档,一个带有 Controller 和服务的模块,为实体“Hero”注入(inject) typeorm 存储库。
使用 Postman,@Get、@Get(':id') 和 @Post 都能完美工作,我的实体->存储库->服务-> Controller 连接到我本地的 Postgres 数据库,我可以获取/添加/更新来自 Hero 表的数据以及这些 API 端点。
但是,PUT 和 DELETE 请求响应为:
{
"statusCode": 404,
"error": "Not Found",
"message": "Cannot PUT /hero"
}
X-Powered-By →Express
Content-Type →application/json; charset=utf-8
Content-Length →67
ETag →W/"43-6vi9yb61CRVGqX01+Xyko0QuUAs"
Date →Sun, 02 Dec 2018 11:40:41 GMT
Connection →keep-alive
对此的请求是 localhost:3000/hero (与 GET 和 POST 相同的端点),我尝试在 Params 中添加 id:1 或使用 x-www-form-urlencoded 在正文中添加 id:1。
请求似乎从未到达 Controller (没有调用任何东西),我在 Nest.js 中添加了一个全局拦截器来执行此操作:
intercept(
context: ExecutionContext,
call$: Observable<any>,
): Observable<any> {
console.log(context.switchToHttp().getRequest());
return call$;
}
但它只记录 GET 和 POST 请求,其他请求永远不会出现。
令我困惑的是,我几乎遵循了 Nest.js 文档,制作了一个基本的 Controller 和服务,连接到数据库的实体/存储库,似乎不需要任何其他东西来实现它的工作,并且但 PUT 和 DELETE 似乎不存在。
最佳答案
从 msg Cannot PUT/hero 来看,您正在发出/hero 请求,而不是例如/hero/1
The request for this is localhost:3000/hero (same endpoint as GET and POST), i've tried either by adding a id:1 in Params or in the Body with x-www-form-urlencoded.
PUT 请求应使用 localhost:3000/hero/<id_here>
完成认为您将查询参数与路径参数混淆了。
类似地,应在localhost:3000/hero/delete/<id_here>
上进行删除
关于node.js - API Controller : Cannot PUT,无法删除(404未找到),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53579955/