Angular 10 HttpClient 无法添加 body 和 header

Angular 10 HttpClient unable to add body and header

使用 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 上,我可以看到 body 详细信息为空。但是,如果我像这样删除 header:

return this.httpClient.post(endPointURL, body)

我可以看到 body 详细信息正确。我需要实现 body 数据和 header。你能告诉我我做错了什么吗?

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)