【发布时间】:2018-10-10 04:02:27
【问题描述】:
使用:
import { HttpClient, HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type: ['application/json']
})
}
@Injectable()
export class MyService {
constructor (private http: HttpClient) {}
private myUrl = 'http://localhost:3000/my-service';
private postBody =
`
[
{ "a": ["complex"],
"serialized": "data",
"set": [],
},{
"in": "json",
"format": []
}
]
`;
getData(): Observable<ExpectedResponseType> {
return this.http.post<ExpectedResponseType>(this.myUrl, this.postBody, httpOptions);
}
}
当我订阅此服务时,浏览器会向 localhost:3000/my-service 发送预检 OPTIONS 请求,该请求返回 404。如果我从请求中删除 httpOptions,它会成功发布我想要但未设置的正文Content-Type 到 application/json,因此服务器返回 500。
如何在 Angular 5 中发送内容类型为 json 的 POST 请求?服务器提供 Postman 的预期结果,但我不确定如何说服 Angular 简单地发送带有我想要的标头的 POST。
【问题讨论】: