如何在尝试访问localhost时避免跨源策略错误? [英] How can you avoid cross-origin policy error when trying to access localhost?

查看:131
本文介绍了如何在尝试访问localhost时避免跨源策略错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在外部服务器上上传一个静态网站,试图从 localhost:3000 获取JSON数据(服务器程序已经在用户上运行计算机)。

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

我正在尝试使用这样的jQuery:

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

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

为什么我会收到跨源政策错误,如何阻止它们?我认为访问JSON数据应该否定那些跨站点错误?

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?

更新1

我刚刚按照建议尝试了带回调的JSONP,但这里有一个奇怪的问题:如果我添加一个指向 localhost:3000 / page URL的脚本标记,加载回调并在页面加载完成后正确显示数据,但这不是我的目标。

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.

如果我尝试使用相同的东西 $。getJSON 方法,我仍然得到与以前相同的错误:

If I try the same thing using the $.getJSON method, I still get the same error as before:

XMLHttpRequest不能加载http:// localhost:3000 / page。 Access-Control-Allow-Origin不允许使用原始http:// localhost。

推荐答案

有趣的想法!

但是 localhost somewebsite.com完全不同的域。因此适用相同的原产地政策。您需要:

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


  • JSONP 这意味着 localhost 上的服务器需要支持在自定义回调中包装JSON

  • CORS 它允许真正的跨域ajax,但是请求的两端都需要大量额外的头部fuzting。

  • 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可能是最容易实现的。来自 $的文档.getJSON()

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


如果网址包含字符串callback =? (或类似的,由
服务器端API定义),请求被视为JSONP。有关详细信息,请参阅$ .ajax()中有关jsonp数据类型的
讨论。

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.

您的 localhost 服务器然后只需要使用jQuery将传入的回调参数。这意味着不是简单地渲染这个:

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

这篇关于如何在尝试访问localhost时避免跨源策略错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆