我正在尝试为下面的 post 请求发送内容类型 header 以允许 json 请求,但它向我抛出一个错误 Invalid CORS request with OPTIONS request method .它甚至不发送 POST 方法。
在这里,我无法使用已折旧的 RequestOptions
。
PS:当我用 postman 发送请求时,这工作正常。而且,后端代码已经使用 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)
关于javascript - angular 7 不按要求发送 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55095745/