0

I am creating a customized homepage, which requires me to get data from various sites (for example, the weather).

I have been using the following code:

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)
})

I also tried req.withCredentials = true before sending it, but it made no difference.

I found various questions regarding this, however with most of these the users had access to the server. The only one I could find without that was:

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

None of the answers said how to get around the problem, so my question is - How can I get around this error?

Community
  • 1
  • 1
Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54
  • 2
    You can't. If you could, you would have identified a very serious security problem. If you cannot change the server, your only choice is to proxy from your *own* server. – Pointy May 02 '16 at 14:44
  • @Pointy Do you know any way for me to set this up. I have XAMPP installed. I was wondering because I would be able to do it using a Firefox Add-on, just open a background tab and load the page. So, I though maybe you could simulate a browser when getting the website data somehow..... – Kaspar Lee May 02 '16 at 14:49
  • 1
    If you're running XAMPP, just do the ajax request to your own PHP server, and use PHP, which isn't subject to the same-origin policy, to do the request, and pass the result back to the ajax request. – adeneo May 02 '16 at 14:52
  • @adeneo Good idea, thank you! – Kaspar Lee May 02 '16 at 15:12

1 Answers1

1

Try using 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/

Lunny
  • 852
  • 1
  • 10
  • 23