Angular 5 - 无法为HttpClient设置标头

Enr*_*ent 11 angular angular-httpclient

我试图HttpClient在Angular 5项目中使用POST调用,我想设置标题:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

出于某种原因,Content-Type标题似乎不在我正在进行的请求中.

在此输入图像描述

为什么是这样?

Ron*_*uza 7

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

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


dim*_*n d 6

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

const _headers = new HttpHeaders();
const headers = _headers.append('Content-Type', 'application/json')
                        .append('...', '...')
                        .append('...', '...');
Run Code Online (Sandbox Code Playgroud)


dee*_* zg 5

如果我看得正确,你向我们展示的是OPTIONS预检请求(CORS),而不是实际的POST请求.

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