以下代码使用CORS协议发送请求并完全接收响应。我想将内容类型标题更改为'application / json'而不是'application / x-www-form-urlencoded'。但是,当我用'application / json'替换内容类型时,请求失败。当我在浏览器中检查请求时,我可以看到内容类型标题已被删除而不是更改。
var servicesApp = angular.module('services', [])
.config(function($httpProvider){
/* Enable CORS */
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
})
.factory('model', function($http) {
var testJSON = '{"employees": [ {"firstName":"John", "lastName":"Doe"} ] }';
$http({
url: 'http://127.0.0.1:8081/controller/UIController',
method: "POST",
params: {"path" : "save"},
data: "message= " + testJSON,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
alert(data.ExampleForm[1]);
}).error(function (data, status, headers, config) {
alert(status);
});
来自上方代码的请求
Request URL:http://127.0.0.1:8081/controller/UIController?path=save
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Connection:keep-alive
Content-Length:67
Content-Type:application/x-www-form-urlencoded
Host:127.0.0.1:8081
Origin:http://127.0.0.1:8020
Referer:http://127.0.0.1:8020/TwineClient/src/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36
Query String Parametersview sourceview URL encoded
path:save
Form Dataview sourceview URL encoded
message: {"employees": [ {"firstName":"John", "lastName":"Doe"} ] }
Response Headersview source
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:POST
Access-Control-Allow-Origin:*
Content-Length:51
Content-Type:application/json;charset=ISO-8859-1
Date:Tue, 11 Feb 2014 16:15:00 GMT
Server:Apache-Coyote/1.1
当'application / x-www-form-urlencoded'替换为'application / json'时:
Request URL:http://127.0.0.1:8081/controller/UIController?path=save
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Access-Control-Request-Headers:accept, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:127.0.0.1:8081
Origin:http://127.0.0.1:8020
Referer:http://127.0.0.1:8020/TwineClient/src/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36
Query String Parametersview sourceview URL encoded
path:save
Response Headersview source
Allow:GET, HEAD, POST, TRACE, OPTIONS
Content-Length:0
Date:Tue, 11 Feb 2014 16:11:02 GMT
Server:Apache-Coyote/1.1
答案 0 :(得分:1)
当您将content-type更改为application / json时,浏览器正在发送预检(OPTIONS)请求。根据CORS规范,这是必需的步骤。如果要将application / json用作请求内容类型,则服务器需要正确确认此预检。您可以在此处阅读有关CORS的更多信息:https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS。
这是关于SO的常见问题解答,我在这里回答了类似的问题:WebAPI 2 - CORS not working with contentType application/json。