API控制器:无法放置,无法删除(404未找到)

Que*_*nec 3 rest node.js express postman nestjs

使用 Nest.js 和一个基本控制器:

\n\n
import { Body, Controller, Delete, Get, Param, Post, Put, Query } from \'@nestjs/common\';\nimport { Hero } from \'../entities/hero.entity\';\nimport { HeroService } from \'./hero.service\';\n\n@Controller(\'hero\')\nexport class HeroController {\n  constructor(private readonly heroesService: HeroService) {}\n\n  @Get()\n  async get(@Query() query): Promise<Hero[]> {\n    return await this.heroesService.find(query);\n  }\n\n  @Get(\':id\')\n  async getById(@Param(\'id\') id): Promise<Hero> {\n    return await this.heroesService.findById(id);\n  }\n\n  @Post()\n  async add(@Body() hero: Hero): Promise<Hero> {\n    return await this.heroesService.save(hero);\n  }\n\n  //TODO: doesn\'t seem to work, never called (request 404)\n  @Put(\':id\')\n  async update(@Param(\'id\') id, @Body() hero): Promise<Hero> {\n    console.log(\'hey\');\n    return await this.heroesService.update(id, hero);\n  }\n\n  //TODO: doesn\'t seem to work, never called (request 404)\n  @Delete(\'/delete/:id\')\n  async remove(@Param(\'id\') id): Promise<Hero> {\n    console.log(\'hey\');\n    return await this.heroesService.remove(id);\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

遵循 Nest.js 的基本文档,一个带有控制器和服务的模块,为实体“Hero”注入 typeorm 存储库。

\n\n

使用 Postman,@Get、@Get(\':id\') 和 @Post 都可以完美工作,我的实体->存储库->服务->控制器连接到我的本地 Postgres 数据库,我可以获取/添加/更新数据来自具有这些 API 端点的 Hero 表。

\n\n

但是,PUT 和 DELETE 请求响应为:

\n\n
{\n    "statusCode": 404,\n    "error": "Not Found",\n    "message": "Cannot PUT /hero"\n}\n\nX-Powered-By \xe2\x86\x92Express\nContent-Type \xe2\x86\x92application/json; charset=utf-8\nContent-Length \xe2\x86\x9267\nETag \xe2\x86\x92W/"43-6vi9yb61CRVGqX01+Xyko0QuUAs"\nDate \xe2\x86\x92Sun, 02 Dec 2018 11:40:41 GMT\nConnection \xe2\x86\x92keep-alive\n
Run Code Online (Sandbox Code Playgroud)\n\n

对此的请求是 localhost:3000/hero (与 GET 和 POST 相同的端点),我尝试过在 Params 中添加 id:1 或使用 x-www-form-urlencoded 在正文中添加 id:1 。

\n\n

请求似乎永远不会到达控制器(没有被调用),我已经向 Nest.js 添加了一个全局拦截器,它只是执行以下操作:

\n\n
intercept(\n    context: ExecutionContext,\n    call$: Observable<any>,\n  ): Observable<any> {\n    console.log(context.switchToHttp().getRequest());\n    return call$;\n  }\n
Run Code Online (Sandbox Code Playgroud)\n\n

但同样,它只记录 GET 和 POST 请求,其他请求永远不会出现。

\n\n

让我困惑的是,我几乎遵循了 Nest.js 文档,制作了一个基本的控制器和服务,连接到数据库的实体/存储库,似乎不需要任何其他东西来实现它的工作,但是PUT 和 DELETE 似乎不存在。

\n

小智 5

从 msg Cannot PUT /hero 来看,您正在发出 /hero 请求,而不是例如 /hero/1

对此的请求是 localhost:3000/hero (与 GET 和 POST 相同的端点),我尝试在 Params 中添加 id:1 或使用 x-www-form-urlencoded 在正文中添加 id:1 。

PUT 请求应该通过localhost:3000/hero/<id_here>“认为您混淆了查询参数与路径参数”来完成。

同样,DELETE 应该在localhost:3000/hero/delete/<id_here>