[英]Setting JSON request header in Angular2 HTTP POST
我在发布请求中设置application / json标头的内容类型时遇到问题。
saveUpdates(alltabs: AllTabs): Observable<Response> {
let api = this.host + this.routes.save;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this._http.post(api, JSON.stringify(alltabs), { headers: headers })
.map((response: Response) => <Response>response.json())
.do(data => console.log("saveUpdates(): " + data))
.catch(this.handleError);
}
请求标头:
OPTIONS /api/productsave HTTP/1.1
Host: wbtest:92
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: POST
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://localhost:3000/product/60000010080
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
响应标题:
HTTP/1.1 405 Method Not Allowed
Cache-Control: no-cache
Pragma: no-cache
Allow: POST
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Date: Tue, 14 Jun 2016 15:16:15 GMT
Content-Length: 76
如您所见,我的请求有两个意外的标头,分别是“ Access-Control-Request-Headers”和“ Access-Control-Request-Method”。 这似乎表明CORS(跨源资源共享)存在问题。 但是,API服务器上的web.conf文件一直在工作,并且响应标头指出“ Access-Control-Allow-Origin:*”。
知道有什么问题吗?
更新:
上面的代码是正确的-问题在于服务器代码未配置为处理预检请求。 就我而言,.NET Web API 2应用程序未配置为允许CORS。
使用CORS,您有两种请求。 实际上,CORS规范区分了两种不同的用例:
text/plain
, application/x-www-form-urlencoded
和multipart/form-data
。 您的服务器似乎未配置为支持预检请求。 405状态码的原因(不允许使用405方法)。
请参阅本文以获取更多详细信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.