【问题标题】:Cross-Origin Request Blocked - How to get around it without having access to the server [duplicate]跨域请求被阻止 - 如何在没有访问服务器的情况下绕过它[重复]
【发布时间】:2016-08-27 09:08:53
【问题描述】:

我正在创建一个自定义主页,这需要我从各个站点获取数据(例如天气)。

我一直在使用以下代码:

var req = new XMLHttpRequest()
req.open('GET', 'http://weather.com/en-GB/weather/today/l/...')
req.send()
req.addEventListener('load', function() {
    console.log(this.responseText)
})

发送之前我也试过req.withCredentials = true,但没有任何区别。

我发现了有关此的各种问题,但是其中大多数用户都可以访问服务器。如果没有那个,我唯一能找到的是:

Firefox CORS request giving 'Cross-Origin Request Blocked' despite headers

没有一个答案说明如何解决这个问题,所以我的问题是 - 我怎样才能解决这个错误?

【问题讨论】:

  • 你不能。如果可以,您将发现一个非常严重的安全问题。如果您无法更改服务器,您唯一的选择是从您的自己的服务器进行代理。
  • @Pointy 你知道我有什么方法可以设置它吗?我已经安装了 XAMPP。我想知道,因为我可以使用 Firefox 插件来做到这一点,只需打开一个后台选项卡并加载页面。所以,我想也许你可以在以某种方式获取网站数据时模拟浏览器.....
  • 如果你运行的是XAMPP,只需向自己的PHP服务器发起ajax请求,并使用不受同源策略约束的PHP发起请求,并通过结果返回到ajax请求。
  • @adeneo 好主意,谢谢!

标签: javascript xmlhttprequest cross-domain


【解决方案1】:

尝试使用jsonp

$.ajax({
   url: 'http://weather.com/en-GB/weather/today/l/SS7:4:UK',
   dataType: 'JSONP',
   jsonpCallback: 'callback',
   type: 'GET',
   success: function (data) {
   console.log(data);
}
});

https://learn.jquery.com/ajax/working-with-jsonp/

【讨论】:

  • 如果服务器不接受 JSONP 请求,那么这将不起作用。
  • 是的,无论我尝试什么,我都会不断收到错误消息:SyntaxError: expected expression, got '<'
猜你喜欢
  • 2015-04-24
  • 1970-01-01
  • 2018-06-25
  • 2017-06-06
  • 2021-06-26
  • 2014-10-13
  • 2019-01-21
相关资源
最近更新 更多