inf*_*dev 1 javascript httprequest angular nestjs
我正在尝试在NestJS中发出Http请求
由于它是受角度启发的,因此我添加了标题
import { Injectable, HttpService} from '@nestjs/common';
...
const headersRequest = new Headers();
headersRequest.append('Content-Type', 'application/json');
headersRequest.append('Authorization', `Basic ${encodeToken}`);
Run Code Online (Sandbox Code Playgroud)
然后调用api
const result = await this.httpService.post(apiUrl, newDevice, { headers: headersRequest });
Run Code Online (Sandbox Code Playgroud)
我得到一个错误
ReferenceError: Headers is not defined
Run Code Online (Sandbox Code Playgroud)
当我Headers导入时,我在VScode中收到此消息警告
Only a void function can be called with the 'new' keyword.
Run Code Online (Sandbox Code Playgroud)
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 });
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您的配置相当静态或硬编码,则另一种选择(自 Nest v5 引入了 HttpModule.registerAsync 以来)encodeToken是在模块级别进行设置:
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 {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3864 次 |
| 最近记录: |