问题描述
限时送ChatGPT账号..这是我的代码:
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
<小时>
logIn(username: string, password: string) {
const url = 'http://server/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 值:
and Data are stored in 'Request Payload' but in my server doesn't received the POST values:
print_r($_POST);
Array
(
)
我认为错误来自未在 POST 期间设置的标头,我做错了什么?
I believe the error comes from the header not set during the POST, what did I do wrong?
推荐答案
新的 HttpHeader
类的实例是 不可变 对象.调用类方法将返回一个新实例作为结果.所以基本上,您需要执行以下操作:
The instances of the new HttpHeader
class are immutable objects. Invoking class methods will return a new instance as result. So basically, you need to do the following:
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 标头的对象映射 &参数
由于 5.0.0-beta.6 现在可以跳过创建HttpHeaders
对象直接传递对象映射作为参数.所以现在可以执行以下操作:
Since 5.0.0-beta.6 is now possible to skip the creation of a HttpHeaders
object an directly pass an object map as argument. So now its possible to do the following:
http.get('someurl',{
headers: {'header1':'value1','header2':'value2'}
});
这篇关于向 Angular HttpClient 添加 HTTP 标头不会发送标头,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论