【问题标题】:$.post (to different domain) not working (node.js / express app on port 8081)$.post(到不同的域)不起作用(端口 8081 上的 node.js / express 应用程序)
【发布时间】:2019-12-29 06:28:24
【问题描述】:

我在以这种方式使用 $.post 时收到错误 POST https://thewebsite.com 400 (Bad Request)

$.post("https://website.com/blabla",
{
  domain: "infoinfo.com",
  room: "someInfo",
  application: "someInfo",
  ident: "someInfo",
},
function (data,status) {
  alert("Data: " + data + "\nStatus: " + status);
});

我尝试在路线中设置res.header('Access-Control-Allow-Origin', "*");,但没有成功。

关于如何解决此问题的任何想法?

Ps.:我发布到的服务器是服务网站(xirsys.com),我很确定他们已经允许外部域。如果我找不到解决方案,我会在白天与他们联系(我正在使用他们建议的 jQuery 帖子:/

【问题讨论】:

  • 必须在您发布数据的服务器上启用跨域

标签: javascript jquery node.js express


【解决方案1】:

尝试将此添加到您的 AJAX 调用中:

contentType: "application/json; charset=utf-8",
dataType: "json"

另一个原因可能是同源政策:

在计算中,同源策略是一个重要的安全概念 对于许多浏览器端编程语言,例如 JavaScript。该策略允许在原始页面上运行脚本 从同一站点访问彼此的方法和属性 没有具体限制,但阻止访问大多数方法和 跨不同网站页面的属性。

您可以从 MDN docs 找到有关此问题的更多信息,或者在 Google 上就该主题进行一些研究。


您可以尝试像这样使用$.axax()

$.ajax({
    type: 'POST',
    url: "https://website.com/blabla",
    data: {
        domain: "infoinfo.com",
        room: "someInfo",
        application: "someInfo",
        ident: "someInfo"
    },
    dataType: "json",
    contentType: "application/json",
    success: function (e) {
        alert("Data: " + data + "\nStatus: " + status);
    }

});

【讨论】:

  • 这个帖子实际上是发给beta.xirsys.com/getIceServers的——我很确定他们已经允许外部域了。您将如何将 contentType/dataType 添加到我的示例中?
  • 其实我的东西没有用,它只从网站获取了默认的 json。试试你的。
  • @DanyP.. 接受有用的答案或发布您的解决方案并接受它作为答案。谢谢
【解决方案2】:

这是由于同源政策。作为安全措施,所有浏览器都不允许任何跨域请求。

http://en.wikipedia.org/wiki/Same-origin_policy

就像在您的情况下,您从不同的域发布到 thewebsite.com 域。一种解决方法是使用 jquery 中的 jsonp(服务器应该支持 json 填充)。

查看这些网站了解更多信息

http://www.jquery4u.com/json/jsonp-examples/
http://en.wikipedia.org/wiki/JSONP
http://stackoverflow.com/questions/6871021/how-to-enable-cross-domain-request-on-the-server

【讨论】:

    【解决方案3】:

    样品请求:

    $.ajax({
                url: "http://yoururl",
                type: "POST",
                crossDomain: true,
                data: JSON.stringify(somejson),
                dataType: "json",
                success: function (response) {
                    alert("success");
                },
                error: function (xhr, status) {
                    alert("error");
                }
            });
    

    Python 中的示例响应:

    response = HttpResponse(json.dumps('{"status" : "success"}'))
    response.__setitem__("Content-type", "application/json")
    response.__setitem__("Access-Control-Allow-Origin", "*")
    
    return response
    

    【讨论】:

      【解决方案4】:

      我发布的链接实际上并不好。我使用的服务更新了他们 API 中的链接以反映正确的链接。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-17
        • 1970-01-01
        • 1970-01-01
        • 2015-07-13
        • 1970-01-01
        • 2014-07-01
        • 1970-01-01
        相关资源
        最近更新 更多