gpt4 book ai didi

angular - 向 Angular HttpClient 添加 HTTP header 不会发送 header ,为什么?

转载 作者:太空狗 更新时间:2023-10-29 16:44:48 32 4
gpt4 key购买 nike

这是我的代码:

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 期间未设置的 header ,我做错了什么?

最佳答案

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

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'});

更新:添加多个标题

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

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

更新:接受 HttpClient header 和参数的对象映射

5.0.0-beta.6现在可以跳过 HttpHeaders 对象的创建,直接将对象映射作为参数传递。所以现在可以执行以下操作:

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

关于angular - 向 Angular HttpClient 添加 HTTP header 不会发送 header ,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45286764/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com