尝试访问本地主机时如何避免跨源策略错误?
我想要在外部服务器上上传一个静态网站,该网站将尝试从 localhost:3000 获取 JSON 数据(服务器程序已经在用户的计算机上运行)。
我正在尝试使用 jQuery 来做到这一点,如下所示:
$.getJSON("http://localhost:3000/page", function(data){
// process data...
});
为什么我会收到跨域策略错误以及如何阻止它们?我认为访问 JSON 数据应该可以消除那些跨站点错误?
更新 1
我刚刚按照建议尝试了带有回调的 JSONP,但这里有一个奇怪的问题:如果我添加一个指向 localhost:3000/page
URL 的脚本标记,当页面加载完成时,回调被加载并且数据被正确显示,但这不是我的目标。
如果我使用 $.getJSON 方法尝试相同的操作,我仍然会收到与以前相同的错误:
XMLHttpRequest 无法加载 http://localhost:3000/page。 Access-Control-Allow-Origin 不允许来源 http://localhost。。
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.
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有趣的想法!
但
localhost
与somewebsite.com
是完全不同的域。因此适用同源政策。您需要:localhost
上的服务器需要支持将 JSON 包装在自定义回调JSONP 可能是最容易实现的。来自
$.getJSON()
的文档:然后,您的 localhost 服务器只需要使用 jQuery 将传入的回调参数。这意味着
本地服务器应该呈现更像这样的内容,而不是简单地呈现:
Interesting idea!
But
localhost
is a totally different domain fromsomewebsite.com
. So the same origin policy applies. You need either:localhost
needs to support wrapping the JSON in a custom callbackJSONP is probably the easiest to pull off. From the docs for
$.getJSON()
:Your
localhost
server then simply needs to use that callback parameter that jQuery will pass in. Meaning that instead of simply rendering this:The local server should render something more like this: