向Angular HttpClient添加HTTP标头不发送标头,为什么?

编程入门 行业动态 更新时间:2024-10-19 08:54:52
本文介绍了向Angular HttpClient添加HTTP标头不发送标头,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是我的代码:

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

logIn(username: string, password: string) { const url = '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标头不发送标头,为什么?

本文发布于:2023-11-16 16:32:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1605977.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:HttpClient   Angular   标头不   HTTP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!