我正在尝试在NestJS中发出Http请求
由于它是受角度启发的,所以我添加了标题
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.
答案 0 :(得分:4)
NestJS在后台使用axios发出http请求,请查看其有关请求配置的文档:
https://github.com/axios/axios#request-config
看起来没有标头的接口,只需传递一个普通的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 });
答案 1 :(得分:0)
我认为这种方法是错误的 在读取标头参数只是req.headers 例子
@Get()
findHeaderexample(@Res() res,@Req req) {
return req.headers;
}
答案 2 :(得分:0)
如果您的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 {}