jQuery 没有向 node.js 服务器发送自定义 header CORS 请求,或者服务器没有收到?

标签 jquery node.js firefox webkit http-status-code-502

整个周末我都在为这个问题苦苦挣扎。该问题仅在通过 mac 计算机访问和通过我的 nodejitsu 实例托管时存在,并且在我的本地主机服务器上不存在。

我的申请很典型。它在不同的域上有一个 Web 服务器组件和 REST 服务器——因此需要 CORS。 唯一增加的复杂性是自定义 header 。

我已经在我的 node.js 服务器上设置了 CORS,如下所示

var allowCrossDomain = function(req, res, next) {

    console.log(req.headers);

    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Accept, X-api-key, X-auth-token, Content-Type, Content-Length');

    // intercept OPTIONS method
    if ('OPTIONS' == req.method) {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Headers', 'Accept, X-api-key, X-auth-token, Content-Type, Content-Length');
        res.send(200, {});
    }
    else {
      next();
    }
};

前端 $.ajax 调用是这样的

//create user
$.ajax({
    url: host + 'users',
    headers: {'X-api-key': apikey},
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify({
        email: userInfo.email,
        username: username,
        password: pasword,
    }),
    xhrFields: {},
    crossDomain: true,
    success: function (res) {
        console.log(res);
        $('.messages')
            .removeClass('error')
            .addClass('success')
            .html('<strong>Success! </strong>Check email for activation link');
    },
    error: function (xhr, status, errorThrown) {
        console.log(xhr.responseText);
        var errorMessage = $.parseJSON(xhr.responseText);
        $('.messages')
            .removeClass('success')
            .addClass('error')
            .html('<strong>Oops!</strong> '+errorMessage.error);

    }
});

从技术上讲,这应该可行。这是对 Node 服务器的教科书 ajax 调用,但是当我在 chrome 中进行调用时,我在 chrome 终端中收到以下预检错误。


    OPTIONS http://api.dev.XXXXX.com/users/login net::ERR_EMPTY_RESPONSE
    jquery-1.7.2.js:8240
    send jquery-1.7.2.js:8240
    jQuery.extend.ajax jquery-1.7.2.js:7719
    (anonymous function) VM62:2
    InjectedScript._evaluateOn VM57:730
    InjectedScript._evaluateAndWrap VM57:669
    InjectedScript.evaluate

On firefox/mozilla it's this and on Safari it's quite similar:


    "NetworkError: 502 Bad Gateway - http://api.dev.XXXX.com/users/fbauth"
    fbauth
    Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://api.dev.XXXX.com/users/fbauth. This can be fixed by moving the resource to the same domain or enabling CORS.

I've somehow managed to partially bypass this by preceding the complex HTTP request simple HTTP request to the server. I don't know why this makes it work, which makes it the world's ugliest, and most partially effective hack.

  $(document).ready(function(){
    setTimeout(function(){
    $.ajax({
      url: host + 'users/login',
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify({

      })
    });

    $.ajax({
      url: host + 'users/fbauth',
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify({

      })
    });

    }, 500);
  })

现在的问题是,在执行简单的 HTTP 后几乎立即执行预检,结果,使用 fb 登录的 oauth 不起作用,因为它在执行所需操作之前向 fb 发出一些请求并返回做。

我完全被困在这里了。这是 webkit/mozilla 引擎问题吗?还是我在这里遗漏了一些关键的东西?

这是一个 jsfiddle,其中包含对测试端点的示例请求。运行时检查控制台。 http://jsfiddle.net/cvince/6nPLJ/

问题——在我的主要开发机器上失败,但它可能对你有用。该请求在我的 6 台计算机中的 4 台上进行了预检并正确验证。

最佳答案

原来是我的VPN客户端引起的。边缘案例! 这是解决方案: http://www.bennadel.com/blog/2559-cisco-anyconnect-vpn-client-may-block-cors-ajax-options-requests.htm

关于jQuery 没有向 node.js 服务器发送自定义 header CORS 请求,或者服务器没有收到?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24114366/

相关文章:

jquery - ASP.NET MVC5 Bootstrap 3 Modal Form 不验证客户端并回发到页面

node.js - 使用 browserify 无法要求 ('aws-iot-device-sdk' )。

node.js - 蒙戈错误: Cannot use a session that has ended (only on 1 collection)

javascript - 语法错误 : Unexpected token angular-cli

jquery - 使用 getScript 时 Firefox 中格式错误

html - 在 Firefox 中,一个 <hr> 标签有效,但另一个无效。这是为什么?

jquery - iOS 上没有 jquery event.target

javascript - jQuery 用户界面 : Draggable and Droppable(not firing) within a table and its rows

javascript - jQuery 按钮单击 jqGrid 的刷新仅触发一次

javascript - 内容流自动启动在 Firefox 中不起作用