Angular 10 HttpClient 无法添加正文和标题

问题描述

使用具有以下数据的 Angular 10 和 HttpClient:

const data = {
  'username': username,'password': password
};
const headers = { 'content-type': 'application/json'}

const body = JSON.stringify(data);
return this.httpClient.post(endPointURL,body,{'headers':headers})

在 endPointURL 上,我可以看到正文详细信息为空。但是如果我像这样删除标题

return this.httpClient.post(endPointURL,body)

我可以正确地看到身体细节。我需要实现正文数据和标题。你能告诉我我做错了什么吗?

解决方法

headers 创建为 -

let headers = new HttpHeaders({
    'Content-Type': 'application/json'
    });

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

并将其作为 {headers: headers} 传递。

此外,您不需要JSON.stringify data

尝试类似 -

const data = {
  'username': username,'password': password
};

let headers = new HttpHeaders({
    'Content-Type': 'application/json'
    });

return this.httpClient.post(endPointURL,data,{headers: headers});
,

按照步骤操作。

  1.     import { HttpClient,HttpHeaders } from "@angular/common/http";
    
  2.     const headers = { headers: new HttpHeaders({"Content-Type":"application/json"})}
        const body= { 'username': username,'password': password};
    
  3.       return this.httpClient.post(endPointURL,body,headers)
    

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...