以下是我的代码:

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
(
)

我相信这个错误来自帖子中没有设置的标题,我做错了什么?

推荐答案

新的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 f或 HttpClient headers & params

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相关问答推荐

间歇性不正确的SSR重定向(server. ts级别的请求和响应不匹配)

如何在投影项目组周围添加包装元素?

如何在init为FALSE时以Angular 初始化主拇指擦除器-Swiper 11.0.6Angular 17 SSR

Rxjs重置执行后的可观察延迟并重新调度Angular

ANGLE DI useFactory将参数传递给工厂函数

如何在AngularJs中剪断细绳

如何将参数传递给Angular 服务

基于RxJS的Angular 服务数据缓存

Angular 信号 在 effect() 中使用 debounce

从具有特定 node 值的现有数组创建新数组

Angular 13 - 使用 PUT 时出现 400 错误(错误请求)

使用 RxJS forkJoin 时传递参数的最佳方式

有条件地取消所有内部可观察对象或切换到仅发出一个值的新对象

全局异常处理

为什么 Angular2 routerLinkActive 将活动类设置为多个链接?

请求 http.GET 时发送的 Angular2 OPTIONS 方法

检测指令中输入值何时更改

Angular 5 中 value 和 ngValue 的区别

从 Angular 中的自定义表单组件访问 FormControl

路由 getCurrentNavigation 始终返回 null