How to set a different Http Status in loopback 4

自古美人都是妖i 提交于 2020-07-17 11:05:06

问题


I can't find any ressources on how to change the success HTTP code using loopback 4.

For example :

201 "created" on post method

204 "no content" on delete method

I tried to specify this in the @api decorator but this change is not reflected in the actual response.

Thank's for your help !


回答1:


I can't find any ressources on how to change the success HTTP code using loopback 4.

We don't have first-class support for this feature yet. The current workaround is to inject the Response object into your controller method and set the status code directly via Express/Node.js core API.

export class TodoController {
  constructor(
    @repository(TodoRepository) protected todoRepo: TodoRepository,
    @inject(RestBindings.Http.RESPONSE) protected response: Response,
  ) {}

  async createTodo(@requestBody() todo: Todo): Promise<Todo> {
    this.response.status(401);
    // ...
  }
}

Don't forget to import Response from @loopback/rest. Add the below import in your controller.

import { Response } from '@loopback/rest';

201 "created" on post method

See the discussion in https://github.com/strongloop/loopback-next/issues/788. The difficult part is how to figure out what URL to send in the Location response header.

204 "no content" on delete method

Just change your controller method to return undefined instead of the current {count: 1} object. I believe this is the default behavior for CRUD controllers scaffolded by our lb4 tool.

export class TodoController {
  // ...
  @del('/todos/{id}', {
    responses: {
      '204': {
        description: 'Todo DELETE success',
      },
    },
  })
  async deleteTodo(@param.path.number('id') id: number): Promise<void> {
    await this.todoRepo.deleteById(id);
  }


来源:https://stackoverflow.com/questions/54655257/how-to-set-a-different-http-status-in-loopback-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!