[英]Setting JSON request header in Angular2 HTTP POST
I'm having a problem setting a content-type of application/json header on my post request. 我在发布请求中设置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);
}
Request Headers: 请求标头:
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
Response Headers: 响应标题:
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
As you can see, my request has two unexpected headers added "Access-Control-Request-Headers" and "Access-Control-Request-Method". 如您所见,我的请求有两个意外的标头,分别是“ Access-Control-Request-Headers”和“ Access-Control-Request-Method”。 This seems to suggest an issue with CORS (Cross-Origin Resource Sharing).
这似乎表明CORS(跨源资源共享)存在问题。 However, the web.conf file on the API server has been working and the response headers states "Access-Control-Allow-Origin: *".
但是,API服务器上的web.conf文件一直在工作,并且响应标头指出“ Access-Control-Allow-Origin:*”。
Any idea what could be wrong? 知道有什么问题吗?
UPDATE: 更新:
The above code is correct - the problem is with the Sever code not being configured to handle preflight requests. 上面的代码是正确的-问题在于服务器代码未配置为处理预检请求。 In my case, the .NET Web API 2 application was not configured to allow CORS.
就我而言,.NET Web API 2应用程序未配置为允许CORS。
With CORS, you have two kinds of requests. 使用CORS,您有两种请求。 As a matter of fact, the CORS specification distinguishes two distinct use cases:
实际上,CORS规范区分了两种不同的用例:
text/plain
, application/x-www-form-urlencoded
and multipart/form-data
. text/plain
, application/x-www-form-urlencoded
和multipart/form-data
。 It seems that your server isn't configured to support preflighted request. 您的服务器似乎未配置为支持预检请求。 The reason for the 405 status code (405 Method Not Allowed).
405状态码的原因(不允许使用405方法)。
See this article for more details: 请参阅本文以获取更多详细信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.