如何在环回4中设置其他Http状态 [英] How to set a different Http Status in loopback 4

查看:44
本文介绍了如何在环回4中设置其他Http状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到有关如何使用环回4更改成功HTTP代码的任何资源.

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

例如:

在发布方法上创建"了201个

201 "created" on post method

204删除方法无内容"

204 "no content" on delete method

我尝试在@api装饰器中指定此设置,但此更改未反映在实际响应中.

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

谢谢您的帮助!

推荐答案

我找不到有关如何使用环回4更改成功HTTP代码的任何资源.

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

我们还没有对此功能的一流支持.当前的解决方法是将Response对象注入到您的控制器方法中,并直接通过Express/Node.js核心API设置状态代码.

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);
    // ...
  }
}

别忘了从 @ loopback/rest 导入 Response .在控制器中添加以下导入.

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

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

在发布方法上创建"了201个

201 "created" on post method

请参见> https://github.com/strongloop/loopback-next/问题/788 .困难的部分是如何确定要在 Location 响应标头中发送的URL.

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删除方法无内容"

204 "no content" on delete method

只需更改您的控制器方法即可返回 undefined 而不是当前的 {count:1} 对象.我相信这是我们 lb4 工具支持的CRUD控制器的默认行为.

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);
  }

这篇关于如何在环回4中设置其他Http状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆