javascript - 在 NestJS 中添加 header HttpRequest

标签 javascript angular httprequest nestjs

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

因为它的灵感来自 angular,所以我 jave 附加了我的标题

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.

最佳答案

NestJS 使用 axios在引擎盖下发出 http 请求,请查看其请求配置文档:

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

貌似没有headers的接口(interface),只传一个普通的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 });

关于javascript - 在 NestJS 中添加 header HttpRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52972616/

相关文章:

javascript - TypeError : $(…). 自动完成不是一个函数

javascript - 如何在 Angular 2 中对指令进行单元测试?

angular - 保持自动完成建议面板打开以进行多项选择,并在 Angular Material 2 的面板外部单击时关闭

curl - 回显curl请求 header 和正文而不发送它?

java - 无法更改 spring-boot 过滤器映射

Angular:HttpRequest.clone() - params 和 setParams 有什么区别?

JavaScript 返回数组中最小和最大数的索引

javascript - Jest Enzyme 测试在 render 方法中返回 null 的 React 组件

javascript - Angular : Detect click event inside a div with ngFor inside

javascript - 是否可以在方形空间上使用 MathJax?