我也遇到了同样的问题!这不是 Chrome 错误,它内置于 chrome 中以确保安全。 (Cross Origin Resource Sharing) 是必须存在于 apache httpd.conf or apache.conf or .htaccess 配置文件中的标头。如果您在 NGINX 上,则必须编辑 defaults.conf or nginx.conf file 它基本上可以使 Web 服务器接受来自其域以外的地方的 HTTP 请求。修复它的“真正”方法是实际进入 Web 服务器(通过 ssh)并编辑适用的 .conf 以包含此标头。如果您使用的是 apache,则应在文件顶部添加 Header set Access-Control-Allow-Origin "*"。完成此操作后,重新启动 apache 以确保保存您的更改 (service httpd restart)。如果你在 NGINX 上使用这个配置:
#
# Wide-open CORS config for nginx
#
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
#
# Om nom nom cookies
#
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
}
现在,根据您的示例,我想您无权访问网络服务器(因为您将 google 的 url 放在 URL 中)。这就是棘手的地方。
您的选择之一是使用http://www.whateverorigin.org/。它绕过 CORS 并有效地检索数据。为了使用它,您将运行:
$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://google.com') + '&callback=?', function(data){
alert(data.contents);
});
无论 Web 服务器上是否存在 CORS,这都会检索响应。
如果您不想更改任何现有代码并且您使用的是 Google Chrome,那么有一种方法可以解决这个 CORS 问题。您可以做的一件事是安装此浏览器扩展:https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?utm_source=plus
你可以绕过 CORS 并运行你的程序。
希望这对你有用!