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

白昼怎懂夜的黑 提交于 2019-12-10 15:56:54

问题


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

I'm trying to do this with jQuery like this:

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

Why am I getting cross-origin policy errors and how can I stop them? I thought accessing JSON data was supposed to negate those cross-site errors?

UPDATE 1

I have just tried the JSONP with callback as suggested but here's a weird issue: If I add a script tag that points to the localhost:3000/page URL, the callback is loaded and the data is displayed properly when the page is done loading, but this is not what I am aiming for.

If I try the same thing using 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..


回答1:


Interesting idea!

But localhost is a totally different domain from somewebsite.com. So the same origin policy applies. You need either:

  • JSONP Which means the server on localhost needs to support wrapping the JSON in a custom callback
  • CORS Which allows true cross domain ajax, but lots of extra header fuzting is required on both ends of the request.

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

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

Your localhost server then simply needs to use that callback parameter that jQuery will pass in. Meaning that instead of simply rendering this:

<%= jsonString() %>

The local server should render something more like this:

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


来源:https://stackoverflow.com/questions/8467625/how-can-you-avoid-cross-origin-policy-error-when-trying-to-access-localhost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!