我在为我的发布请求设置 application/json header 的内容类型时遇到问题。
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);
}
请求 header :
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
如您所见,我的请求添加了两个意外 header “Access-Control-Request-Headers”和“Access-Control-Request-Method”。这似乎表明 CORS(跨源资源共享)存在问题。但是,API 服务器上的 web.conf 文件一直在工作,响应 header 显示“Access-Control-Allow-Origin: *”。
知道哪里出了问题吗?
更新:
上面的代码是正确的——问题是服务器代码没有被配置为处理预检请求。就我而言,.NET Web API 2 应用程序未配置为允许 CORS。
最佳答案
使用 CORS,您有两种请求。事实上,CORS 规范区分了两种不同的用例:
- 简单请求。如果我们使用 HTTP GET、HEAD 和 POST 方法,则此用例适用。对于 POST 方法,仅支持具有以下值的内容类型:
text/plain
、application/x-www-form-urlencoded
和multipart/表单数据
. - 预检请求。当“简单请求”用例不适用时,将发出第一个请求(使用 HTTP OPTIONS 方法)以检查在跨域请求的上下文中可以做什么。
您的服务器似乎未配置为支持预检请求。 405状态码(405 Method Not Allowed)的原因。
有关详细信息,请参阅本文:
关于http - 在 Angular2 HTTP POST 中设置 JSON 请求 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37816239/