Angular 5 - 无法为 HttpClient 设置 header

Angular 5 - Can't set header for HttpClient

我正在尝试在 Angular 5 项目中使用 HttpClient 进行 POST 调用,我想设置 header:

import { HttpClient, HttpHeaders, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { AuthData }    from './models/auth-data';

@Injectable()
export class AuthService {

    constructor(private http: HttpClient) { }

    auth = (data: AuthData) => {

        var url = "https://.../login";
        var payload = data;
        var headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
        var options =  {
            headers: headers
        };

        this.http.post(url, payload, options).subscribe();
    }
}

出于某种原因,Content-Type header 似乎不在我提出的请求中。

这是为什么?

试试这个:

var headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');

如果我没看错的话,您向我们展示的是 OPTIONS 预检请求 (CORS),而不是实际的 POST 请求。

应该有 2 个'requests in question'。一个的http方法应该是OPTIONS(你在这里展示的那个,它叫做preflight cors请求)和一个实际的POST(如果服务器允许你的客户端)。如果主机不同于 locahost:4200,我假设是,那么您必须在服务器上为 localhost:4200 客户端启用 cors 请求。

也试试这个我遇到了同样的问题 ;)

ng build --production -host=yourDomain.com

问题是该项目是在本地主机上构建的,使用节点,并保留这些默认主机和端口信息,您可以在构建项目时更改它

因为 HttpHeaders 是不可变的,我们必须分配它

const _headers = new HttpHeaders();
const headers = _headers.append('Content-Type', 'application/json')
                        .append('...', '...')
                        .append('...', '...');

这对我有用。而不是追加。

let headers = new HttpHeaders({
'Content-Type': 'application/json'
});
const httpOptions = {
        headers: new HttpHeaders({
          'Content-Type':  'application/json',
          'id':id
        })
      };          

注意:请将 'id' 发送为 'String',注意以下修改

 const httpOptions = {
        headers: new HttpHeaders({
          'Content-Type':  'application/json',
          'id':id+''
        })
      }; 

一切正常。