0

What i want to know is, that can i send a get request with ajax for instance to stackoverflow.com with ajax and get the response, like for example:

Sending a Get request to stackoverflow with Node JS.

const https = require("https");

https.get("https://stackoverflow.com", res => {
    res.on("data", data => {
        console.log(data.toString());
    })
})

I got all the Html code in the response.

Now if i try to send the same requests but through AJAX.

$.getJSON("https://stackoverflow.com", response => {
  console.log(response);
});

I end up with this error:

XMLHttpRequest cannot load https://stackoverflow.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource.

Osama Xäwãñz
  • 437
  • 2
  • 8
  • 21
  • Short answer: No. You'll be blocked by the [Same Origin Policy](http://en.wikipedia.org/wiki/Same-origin_policy) unless the response includes CORS headers - which the vast majority do not. – Rory McCrossan Sep 08 '17 at 12:39
  • 1
    you can send GET requests, just can't get the responses unless it is JSONP or CORS enabled or an image, script, or stylesheet with script/image tags. – epascarello Sep 08 '17 at 12:41
  • Rory McCrossan, can you please explain me further more, i'm still confused that how it's is possible to send the same request with node js. – Osama Xäwãñz Sep 08 '17 at 12:43
  • 1
    It's because Node runs on the server. Client side JS cross domain requests are blocked by the SOP (as linked to above) for security reasons. – Rory McCrossan Sep 08 '17 at 12:44
  • AKA, do you want some random person to access your gmail account, bank, facebook with Ajax requests when you view some random site? No, hence why there is the [same origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy). – epascarello Sep 08 '17 at 12:53
  • The way I used to go was "making the request from your backend", you can make the call to a script on your server that then makes the GET request to the site, process the received data and return it to you, I used to do it like that a couple years ago with the Instagram API... if you are trying to do it like requesting the site, I believe it won't work either. – DIEGO CARRASCAL Sep 08 '17 at 13:03

0 Answers0