【问题标题】:CORS issue: No 'Access-Control-Allow-Origin' header is present on the requested resourceCORS 问题:请求的资源上不存在“Access-Control-Allow-Origin”标头
【发布时间】:2016-05-20 21:04:27
【问题描述】:
var enableCORS = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');

// intercept OPTIONS method
if ('OPTIONS' == req.method) {
  res.send(200);
}
else {
  next();
}
};
app.use(enableCORS);

我发现在服务器端使用了以下 sn-p,但是当我尝试 POST 时,我仍然收到错误 No 'Access-Control-Allow-Origin' header is present on the requested resource。

【问题讨论】:

    标签: node.js post xmlhttprequest cors


    【解决方案1】:

    我只使用以下行:

    res.header("Access-Control-Allow-Origin", "*");
    

    而且它有效。在发送标题之前你有没有机会打印其他东西?标头必须在其他任何内容之前发送。中间件代码应该在其他任何东西之前。

    您确定代码正在执行吗?做一些'console.log'打印以确保enableCORS被调用。

    最后,使用 chrome 开发人员工具(或任何等效工具)查看从服务器返回的标头。对于 chrome,转到网络 => 有问题的请求 => 标头 => 响应标头,并确保 CORS 标头在那里。

    更新 尝试使用以下内容(取自here):

    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); # OPTIONS removed
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    

    【讨论】:

    • “预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段内容类型。”这就是我在 chrome 控制台得到的结果
    • 可能缺少标题。在创建标题之前尝试“console.log”,看看它是否被执行。我已经用在 chrome 上检查的内容更新了答案
    • console.log 正在打印,但发布请求仍然无法正常工作,并且我遇到了同样的错误。这些是响应标头: Access-Control-Allow-Origin:* Allow:POST,GET,HEAD Connection:keep-alive Content-Length:13 Content-Type:text/html; charset=utf-8 日期:格林威治标准时间 2016 年 2 月 10 日星期三 15:52:56 ETag:W/"d-hXhJBegAzPe2v3FerP2DCw" X-Powered-By:Express
    猜你喜欢
    • 2017-08-19
    • 1970-01-01
    • 2018-10-16
    • 2014-07-06
    • 2017-04-11
    相关资源
    最近更新 更多