首页 文章

Angular HttpClient不发送标头

提问于
浏览
93

这是我的代码:

import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';

logIn(username: string, password: string) {
    const url = 'http://server.com/index.php';
    const body = JSON.stringify({username: username,
                                 password: password});
    const headers = new HttpHeaders();
    headers.set('Content-Type', 'application/json; charset=utf-8');
    this.http.post(url, body, {headers: headers}).subscribe(
        (data) => {
            console.log(data);
        },
        (err: HttpErrorResponse) => {
            if (err.error instanceof Error) {
                console.log('Client-side error occured.');
            } else {
                console.log('Server-side error occured.');
            }
        }
    );
}

在这里网络调试:

Request Method:POST
Status Code:200 OK
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:46
Content-Type:text/plain

和数据存储在“请求有效负载”中,但在我的服务器中没有收到POST值:

print_r($_POST);
Array
(
)

我相信错误来自POST期间没有设置的 Headers ,我做了什么错了?

5 回答

  • 0

    HttpHeader 类的实例是 immutable 对象 . 调用类方法将返回一个新实例作为结果 . 基本上,您需要执行以下操作:

    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json; charset=utf-8');
    

    要么

    const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});
    

    Update: adding multiple headers

    let headers = new HttpHeaders();
    headers = headers.set('h1', 'v1').set('h2','v2');
    

    要么

    const headers = new HttpHeaders({'h1':'v1','h2':'v2'});
    

    Update: accept object map for HttpClient headers & params

    由于5.0.0-beta.6现在可以跳过创建 HttpHeaders 对象,因此直接将对象映射作为参数传递 . 所以现在可以做到以下几点:

    http.get('someurl',{
       headers: {'header1':'value1','header2':'value2'}
    });
    
  • 0

    要添加多个参数或 Headers ,您可以执行以下操作:

    constructor(private _http: HttpClient) {}
    
    //....
    
    const url = `${environment.APP_API}/api/request`;
    
    let headers = new HttpHeaders().set('header1', hvalue1); // create header object
    headers = headers.append('header2', hvalue2); // add a new header, creating a new object
    headers = headers.append('header3', hvalue3); // add another header
    
    let params = new HttpParams().set('param1', value1); // create params object
    params = params.append('param2', value2); // add a new param, creating a new object
    params = params.append('param3', value3); // add another param 
    
    return this._http.get<any[]>(url, { headers: headers, params: params })
    
  • 165

    在http请求中设置如下所示的http标头

    return this.http.get(url, { headers: new HttpHeaders({'Authorization': 'Bearer ' + token})
     });
    
  • 5

    在手册(https://angular.io/guide/http)中,我读到:HttpHeaders类是不可变的,因此每个set()都返回一个新实例并应用更改 .

    以下代码适用于angular-4:

    return this.http.get(url, {headers: new HttpHeaders().set('UserEmail', email ) });
    
  • 14

    我很长时间都在挣扎 . 我正在使用Angular 6,我发现了

    let headers = new HttpHeaders();
    headers = headers.append('key', 'value');
    

    不工作 . 但是工作做了什么

    let headers = new HttpHeaders().append('key', 'value');
    

    当你意识到它们是不可变的时,这是有意义的 . 所以创建了一个 Headers ,你无法添加它 . 我没有尝试过,但我怀疑

    let headers = new HttpHeaders();
    let headers1 = headers.append('key', 'value');
    

    也会工作 .

相关问题