我正在从我的 asp.net 表单中调用此函数,并在调用 ajax 时在 firebug 控制台上出现以下错误。
跨域请求被阻止:同源策略不允许读取位于 http://anotherdomain/test.json 的远程资源。 (原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。
var url= 'http://anotherdomain/test.json';
$.ajax({
url: url,
crossOrigin: true,
type: 'GET',
xhrFields: { withCredentials: true },
accept: 'application/json'
}).done(function (data) {
alert(data);
}).fail(function (xhr, textStatus, error) {
var title, message;
switch (xhr.status) {
case 403:
title = xhr.responseJSON.errorSummary;
message = 'Please login to your server before running the test.';
break;
default:
title = 'Invalid URL or Cross-Origin Request Blocked';
message = 'You must explictly add this site (' + window.location.origin + ') to the list of allowed websites in your server.';
break;
}
});
我已经完成了替代方法,但仍然无法找到解决方案。
注意:我没有进行服务器端(API/URL)更改的服务器权限。
anotherdomain
是否支持 jsonp?否则请阅读此重复线程 stackoverflow.com/questions/20035101/…
anotherdonain
不支持 CORS。我收到 title = 'Invalid URL or Cross-Origin Request Blocked';
消息。
cors
的情况下接收 json 包装的数据
当您尝试访问另一个域的资源时,通常会发生这种情况。
这是一项安全功能,可避免每个人自由访问该域的任何资源(例如,可以访问这些资源以在盗版域上拥有与您的网站完全相同的副本)。
响应的标头,即使是 200OK,也不允许其他来源(域、端口)访问资源。
如果您是两个域的所有者,则可以解决此问题:
解决方案 1:通过 .htaccess
要更改它,您可以在 requested domain 文件的 .htaccess
中写入:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
如果您只想授予对一个域的访问权限,.htaccess
应如下所示:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin 'https://my-domain.example'
</IfModule>
解决方案 2:以正确的方式设置标题
如果您将其设置到请求文件的响应头中,您将允许每个人访问资源:
Access-Control-Allow-Origin : *
或者
Access-Control-Allow-Origin : http://www.my-domain.example
在您的 ajax 请求中,添加:
dataType: "jsonp",
行后:
type: 'GET',
应该解决这个问题..
希望这对你有帮助
服务器端将其放在 .php 之上:
header('Access-Control-Allow-Origin: *');
您可以设置特定的域限制访问:
header('Access-Control-Allow-Origin: https://www.example.com')
您必须修改服务器端代码,如下所示
public class CorsResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
responseContext.getHeaders().add("Access-Control-Allow-Origin","*");
responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
}
}
在完成上述答案后,您一定知道为什么会遇到这个问题。
self.send_header('Access-Control-Allow-Origin', '*')
您只需在服务器端添加上述行。
这对我有用:
创建 php 文件,该文件将在不使用 js 的情况下下载另一个域页面的内容:
<?
//file name: your_php_page.php
echo file_get_contents('http://anotherdomain/test.json');
?>
然后在 ajax (jquery) 中运行它。例子:
$.ajax({
url: your_php_page.php,
//optional data might be usefull
//type: 'GET',
//dataType: "jsonp",
//dataType: 'xml',
context: document.body
}).done(function(data) {
alert("data");
});
如果您在后端使用 Express js,您可以安装软件包 cors,然后在您的服务器中使用它,如下所示:
const cors = require("cors");
app.use(cors());
这解决了我的问题
不定期副业成功案例分享
Correct Answer
<IfModule mod_headers.c> Header set Access-Control-Allow-Origin "*" </IfModule>
,它就像一个魅力 :)