How can you avoid cross-origin policy error while trying to access localhost?

I want a static website to load on an external server, which will try to get JSON data from localhost:3000 (the server program will already be running on the user's computer).

I am trying to do this using jQuery as follows:

 $.getJSON("http://localhost:3000/page", function(data){ // process data... }); 

Why am I getting errors with errors between the source codes and how to stop them? I thought that accessing JSON data was supposed to negate these errors between sites?

UPDATE 1

I just tried JSONP with a callback, as suggested, but here's a weird problem: if I add a script tag that points to the localhost:3000/page URL, the callback will load and the data will display correctly when the page but it’s not what I am striving for.

If I try to use the same with the $.getJSON method, I still get the same error as before:

XMLHttpRequest cannot load http://localhost:3000/page. Origin http://localhost is not allowed by Access-Control-Allow-Origin. .

+4
source share
1 answer

Interesting idea!

But localhost is a completely different area from somewebsite.com . So the same origin policy applies. You need:

  • JSONP This means that the server on localhost must support JSON termination in the user callback
  • CORS , which allows you to use the true ajax cross domain, but at both ends of the request, a lot of extra header break is required.

JSONP is probably the easiest to remove. From the docs for $.getJSON() :

If the URL contains the string "callback =?" (or similar, as defined by the server-side API), the request is instead processed as JSONP. See the discussion of jsonp data type in $ .ajax () for more details.

Then, the localhost server just needs to use this callback parameter, which will be passed to jQuery. This means that instead of just displaying it:

 <%= jsonString() %> 

The local server should display something like this:

 <% if (params.callback) { %> <%= params.callback %>(<%= jsonString %>); <% } else { %> <%= jsonString %> <% } %> 
+3
source

Source: https://habr.com/ru/post/1385796/


All Articles