【问题标题】:CORS with Node.js and jQuery带有 Node.js 和 jQuery 的 CORS
【发布时间】:2012-09-02 10:02:30
【问题描述】:

我需要向不提供 javascript 的 Node 服务器发送一些数据。我运行服务器,但从未看到 OPTIONS 发送,并且 Chrome 拒绝我的 ajax 来自不同的域。]

我的服务器:

var http = require('http');
var router = require('router');
var routing = router();
var server = http.createServer(routing);
routing.options('*', function(request, response){
  console.log("OPTIONS BEING SENT");
  var origin = (request.headers.origin || "*");
  response.writeHead("204",
                     "No Content",
                     { "access-control-allow-origin": origin,
                     "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
                     "access-control-allow-headers": "content-type, accept",
                     "access-control-max-age": 10,
                     "content-length": 0
                   });
  response.end();
});

server.listen(7738);

我的 js 发送的是 jqxhr = $.get('localhost:7738/post/trackEvent/' + eventName);,但我从来没有看到 OPTIONS 被发送。如果我使用其他工具通过 OPTIONS 请求访问服务器,它会按预期工作。

更新:

http://localhost:7738/post/trackEvent/MoneyInTheBank 发送 OPTIONS 请求来访问服务器会返回:

HTTP/1.1 204 No Content
Content-Length: 0
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS
Access-Control-Allow-Headers: Content-Type, Accept
Access-Control-Max-Age: 10
Connection: close

【问题讨论】:

标签: jquery node.js cors


【解决方案1】:

只有预检请求发送 OPTIONS 标头,并且由于您的 ajax 请求是一个带有简单标头的简单方法,因此不会向服务器发送任何 OPTIONS。

详情请查看W3CMDN

【讨论】:

  • 我将方法更改为 PUT,但它仍然抱怨 OPTIONS localhost:7738/post/trackEvent/MoneyInTheBank Resource failed to load 。如果我可以使用 OPTIONS ping 该地址并且它的行为符合预期,为什么会这样?
  • 擦除一个简单的 Rails 应用程序可以解决这个问题。 Chrome 只是不喜欢来自文件的来源。
猜你喜欢
  • 2016-04-10
  • 1970-01-01
  • 2015-12-25
  • 2011-04-28
  • 2014-11-10
  • 2012-07-28
  • 2017-07-25
  • 2016-04-20
  • 2015-08-30
相关资源
最近更新 更多