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

API Controller : Cannot PUT, Cannot DELETE (404 not found)

有了Nest.js和一个基本控制器:

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 的基本文档,一个带有控制器和服务的模块,为实体 'Hero'.

注入一个 typeorm 存储库

使用Postman,@Get、@Get(':id') 和@Post 都能正常工作,我的entity->repository->service->controller 连接到我的本地Postgres 数据库,我可以使用那些 API 端点 get/add/update 来自 Hero table 的数据。

但是,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 或 Body 中添加 id:1 x-www-form-urlencoded.

请求似乎永远不会到达控制器(没有调用),我已经向 Nest.js 添加了一个全局拦截器,它就是这样做的:

intercept(
    context: ExecutionContext,
    call$: Observable<any>,
  ): Observable<any> {
    console.log(context.switchToHttp().getRequest());
    return call$;
  }

但它同样只记录 GET 和 POST 请求,其他的从未出现。

让我感到困惑的是,我几乎已经按照Nest.js文档,做了一个基本的控制器和服务,entity/repository连接到数据库,似乎没有其他需要的东西为此,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>

上执行 DELETE