将Chrome更新到版本30.0.1599.101后,我遇到了类似的问题,结果证明是服务器问题。
我的服务器使用快车(http://expressjs.com/),并允许CORS下面的代码(How to allow 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。
您好,欢迎来到SO,请注意在发布时将所有示例代码放在代码块中。 – user65439
这个电话是在同一个域名上吗?我想你可能会试图调用另一个域,以便浏览器出于安全原因而阻止它。尝试JSONP,如果是这样的话。 – hjgraca