javascript - Angular http 模块 - 发布标题
问题描述
在 Angular(使用 Ionic)中使用 http 模块进行发布请求时,我无法更改标头。这是我的代码:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
const apiUrl = "https://webhook.site/c2d56330-84d4-47cf-9f98-472f7eac8000";
@Injectable({
providedIn: 'root'
})
export class APIService {
constructor(private http: HttpClient) { }
getToken(){
var body = {
'data1': 'data2',
'somedata3': 'data4',
};
let headers = new HttpHeaders().append('Content-Type', 'application/json');
this.http.post(apiUrl, JSON.stringify(body), {headers}).subscribe(data =>
console.log(data));
console.log(headers.get('Content-Type')); //return 'application/json'
}
}
一切正常,但它仍然发送标题“content-type:text/plain”而不是“content-type:application/json”。
我输入错误了吗?
解决方案
我更喜欢这样的东西:
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
this.http.post<Foo>(this.apiUrl, body, httpOptions)
此外,我认为不需要对主体进行字符串化,只需将其作为“普通”对象传递
推荐阅读
- apache-kafka - 为什么在 Kafka 中使用 FETCH_SESSION_ID_NOT_FOUND?
- db2 - 防止两个线程选择同一行 ibm db2
- netsuite - NetSuite 保存的搜索显示内部销售代表(如果有)
- c# - 将 SQL 查询转换为 C#?对于存储过程?
- c++ - 从堆栈分配的原始指针构造智能指针
- c# - 使用 EPPlus.Core 在 Excel 文件中创建多个标题行
- python - Python中的三元运算符中是否可以进行多个变量赋值?
- sql - 带日期函数的 SQL 连接
- stm32 - STM32F103 SPI主从接收问题
- excel - 如何根据特定单元格中是否存在单词,将一个单元格的值替换为另一个单元格的值