javascript - 角度 7 未按要求发送标头
问题描述
我正在尝试为以下发布请求发送内容类型标头以允许 json 请求,但它向我抛出了一个错误Invalid CORS request with OPTIONS request method。它甚至不发送POST方法。
在这里,我无法使用RequestOptions
折旧的。
PS:当我用邮递员发送请求时,这工作正常。而且,后端代码已经通过 CORS 请求处理。
从后端java代码,这是我得到的错误
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported
我在哪里失踪?
postSubmit(){
let data = { "name":"John", "age":30 };
const httpHeaders = new HttpHeaders ({
'Content-Type': 'application/json'
});
return this.http.post<any>(apiURL, data, {headers : httpHeaders})
.pipe(catchError(error => this.handleError(error)))
}
}
解决方案
要使用新的 HttpHeaders 类定义内容类型,您需要
- 只需导入
import { HttpHeaders } from '@angular/common/http'
; 创建将传递给每个 HttpClient 保存方法的 httpOptions 对象
import { HttpHeaders } from '@angular/common/http'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': 'my-auth-token' }) };
调用 API
this.http.post<Datatype>(API url, Bady Parameter, httpOptions)
推荐阅读
- ruby - 有没有更好的方法来分配 Ruby 哈希,同时避免 RuboCop 的 ABC 大小警告?
- php - 使用 Guzzle 时 Laravel 通知不起作用
- xml - 在 XSL 中使用时区格式化日期
- wordpress - 用于从网络成员登录区域发送安全邮件/或消息的 Wordpress 插件
- reactjs - 如何为谷歌材料条形图制作动画
- spring - 跨多个过滤器在 Spring Cloud 网关中维护状态/上下文
- powershell - PowerShell - 删除 IP - 使用 Remove-NetIPAddress 的地址
- java - 无效的 Java 语句
- angular - 431 使用查询参数的请求标头字段太大
- python - 定向梯度直方图(HOG)描述符的最小图像尺寸是多少?