首页 > 解决方案 > 如何在 LoopBack 的控制器函数中访问标头?

问题描述

我在环回中有一个函数,它使用它自己特殊的身份验证形式。我不想让这个身份验证阶段与端点本身分开完成。我想在端点代码中进行身份验证。

为此,我需要访问 Authorization 标头。

如何在环回控制器功能中执行此操作?

  @get('/item/{itemId}', {
    description: `Get a specific item`,
    responses: {}
  })
  async getItem(
    @param.path.string('itemId') itemId: string,
  ): Promise<LabResult[]> {
    // How do I get headers from here?
    const auth = somehowGetHeaders().get("Authorization");
  }

标签: http-headersloopback

解决方案


您可以通过注入请求对象来访问标头。例如 。. .

@get('/item/{itemId}', {
  description: `Get a specific item`,
  responses: {}
})
async getItem(
  @param.path.string('itemId') itemId: string,
  @inject(RestBindings.Http.REQUEST) private req: Request
): Promise<LabResult[]> {
  console.log('headers', req.headers);
  // using header information here you can authenticate
}

推荐阅读