在将 Chrome 更新到版本 30.0.1599.101 后,我遇到了类似的问题,结果证明是服务器问题。
我的服务器是使用 Express ( http://expressjs.com/ ) 实现的,下面的代码允许 CORS (如何允许 CORS? ) 运行良好:
var express = require("express");
var server = express();
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', req.headers.origin || "*");
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'content-Type,x-requested-with');
next();
}
server.configure(function () {
server.use(allowCrossDomain);
});
server.options('/*', function(req, res){
res.header('Access-Control-Allow-Origin', req.headers.origin || "*");
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'content-Type,x-requested-with');
res.send(200);
});
server.post('/some_service', function (req, res) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
// stuff here
//example of a json response
res.contentType('json');
res.send(JSON.stringify({OK: true}));
});
HTTP 请求如下所示:
$http({
method: 'POST',
url: 'http://localhost/some_service',
data: JSON.stringify({
key1: "val1",
key2: "val2"
}),
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).success(
function (data, status, headers, config) {
//do something
}
).error(
function (data, status, headers, config) {
//do something
}
);
正如此处( https://stackoverflow.com/a/8572637/772020 )所指出的,这个想法是确保您的服务器正确处理 OPTIONS 请求以启用 CORS。