首页 > 解决方案 > 无法使用 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,因为这是我试图调用的第三方服务。

任何帮助,将不胜感激。谢谢

标签: restapihttpangular7

解决方案


解决了这个问题。将 POST 调用更改为以下内容:

requestToken() {

    const httpHeaders = new HttpHeaders({
      'Accept': 'application/json'
    });

    return this.http.post(this.configUrl + '/token', { body: ''}, { headers: httpHeaders });
  }

必须添加一个空的“body”参数


推荐阅读