在NestJS中添加标头HttpRequest.
我正在尝试在NestJS中发出http请求
因为它的灵感来自于角度,所以我附上了我的标题
import { Injectable, HttpService} from '@nestjs/common';
...
const headersRequest = new Headers();
headersRequest.append('Content-Type', 'application/json');
headersRequest.append('Authorization', `Basic ${encodeToken}`);
然后调用接口
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.
解决方案
NestJS暗中使用axios发出Http请求,请查看其请求配置文档:
https://github.com/axios/axios#request-config
看起来没有Header接口,只需传递一个普通的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 });
相关文章