【问题标题】:Add headers HttpRequest in NestJS在 NestJS 中添加标头 HttpRequest
【发布时间】:2019-03-29 01:59:09
【问题描述】:

我正在尝试在 NestJS 中发出 Http 请求

因为它的灵感来自 Angular,所以我添加了我的标题

import { Injectable, HttpService} from '@nestjs/common';
...
const headersRequest = new Headers();
headersRequest.append('Content-Type', 'application/json');
headersRequest.append('Authorization', `Basic ${encodeToken}`);

然后调用api

const result = await this.httpService.post(apiUrl, newDevice, { headers: headersRequest });

我收到一个错误

ReferenceError: Headers is not defined

当我使用 Headers 进行导入时 我在 VScode 中收到此消息警告

Only a void function can be called with the 'new' keyword.

【问题讨论】:

    标签: javascript angular httprequest nestjs


    【解决方案1】:

    NestJS 在后台使用axios 发出http 请求,请查看其请求配置文档:

    https://github.com/axios/axios#request-config

    貌似没有headers的接口,只传一个普通的JS字典对象:

    const headersRequest = {
        'Content-Type': 'application/json', // afaik this one is not needed
        'Authorization': `Basic ${encodeToken}`,
    };
    
    const result = await this.httpService.post(apiUrl, newDevice, { headers: headersRequest });
    

    【讨论】:

      【解决方案2】:

      我认为这种方法是错误的 在 for read headers 参数中只是 req.headers 例子

       @Get()
          findHeaderexample(@Res() res,@Req req) {
              return req.headers;
      }
      

      【讨论】:

      • 谢谢 Riadh 但这不完全是我要做的,我会设置标题以在控制器内(完全在服务内)创建一个 httpRequest,而不是获取 req 标题
      • 可以解释一下你的想法
      【解决方案3】:

      如果您的encodeToken 是静态的或从您的配置硬编码的另一个选项(因为nest v5 引入了HttpModule.registerAsync)是在模块级别设置它:

      import { Module, HttpModule } from '@nestjs/common';
      import { ConfigModule } from '..';
      import { ConfigService } from '../config/config.service';
      
      
      @Module({
        imports: [
          ConfigModule,
          HttpModule.registerAsync({
            imports: [ConfigModule],
            useFactory: async (configService: ConfigService) => ({
              baseURL: configService.get('vendors.apiEndpoint'),
              headers: {          
                'Authorization': 'Basic ' + configService.get('vendors.encodeToken')
              },
              timeout: 7000,
              maxRedirects: 5
            }),
            inject: [ConfigService]
          })
        ],
        // ... other module stuff
      })
      
      export class MyModule {}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-16
        • 2015-05-19
        • 1970-01-01
        • 2014-02-28
        • 1970-01-01
        • 1970-01-01
        • 2019-11-08
        相关资源
        最近更新 更多