rest - 无法使用 Angular 7 发布:标题不起作用
问题描述
我目前正在构建一个 Angular 7 应用程序,并尝试实现以下 HTTP API 调用场景:
请求应用程序令牌: https://(URL)/token
请求类型:POST
标头:接受:应用程序/json
请求正文:空
我在 Angular 应用程序中有一个服务类,代码如下:
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
requestToken函数实现如下:
requestToken() {
let headers = new HttpHeaders();
headers = headers.set('Accept', 'application/json');
return this.http.post(this.configUrl + '/token', headers);
}
然后在应用程序的组件之一中调用服务:-
getToken() {
this.service.requestToken().subscribe( res => {
console.log(res);
}, error => {
console.log(error);
});
}
当我运行应用程序时,我在控制台中收到 404 Not Found 错误。我使用 Postman 进行 API 调用,将“Accept”标头设置为“application/json”,然后将 url 指定为https://(URL)/token,我成功获得了响应。但我无法通过 Angular 使其工作。
我还需要做些什么才能在 Angular 中正确设置标题吗?此外,我无法检查 API 服务器上是否启用了 CORS,因为这是我试图调用的第三方服务。
任何帮助,将不胜感激。谢谢
解决方案
解决了这个问题。将 POST 调用更改为以下内容:
requestToken() {
const httpHeaders = new HttpHeaders({
'Accept': 'application/json'
});
return this.http.post(this.configUrl + '/token', { body: ''}, { headers: httpHeaders });
}
必须添加一个空的“body”参数
推荐阅读
- clickhouse - 如何理解 ClickHouse 的部分和分区?
- django - 升级到 Django 2 后的 TypeError 和 AssertionError
- jquery - 删除“amp;” 从网址
- jquery-ui - 第二次触发时自动完成不显示建议列表
- laravel - BadMethodCallException 调用模型方法上的未定义方法,该方法使用多对多关系引用自身
- qt - 如何使用自制软件在 macOS 上安装 qt4?
- javascript - 如何从带有 for 循环的数组中附加一个 div 容器(在 JavaScript 中)
- javascript - 动态加载内容的 Powertip 无需再次运行脚本或循环
- google-cloud-dataflow - Google Cloud Pub/Sub 从 API 端点提取数据并作为消息发布
- node.js - Node.js,path.resolve()“TypeError:无法读取未定义的属性'resolve'”