【问题标题】:How is the CORS "Access-Control-Allow-Origin" value exposed to the browser?CORS“Access-Control-Allow-Origin”值如何暴露给浏览器?
【发布时间】:2014-09-03 20:06:00
【问题描述】:

在 Node.js 中,我了解在响应标头中发送“Access-Control-Allow-Origin”值的语法,但我很困惑这个值在被处理之前是如何暴露给浏览器的由服务器决定,因为响应头是稍后决定的,在处理请求之后,什么时候真正发送响应。

例如,使用 Express:

/* Server */

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());
app.post('/login', function (req, res) {

    var username = req.body.username;
    var password = req.body.password;

    if (username !== "undefined"){

        respondSuccess(req,res);

    } else {

        respondFailure(req,res);

    }

});

app.listen(2222);

这里是否有“Access-Control-Allow-Origin”标头取决于用户名未定义的结果。

function respondSuccess(){

    body = "Success!";
    res.writeHead(200, {

        'Access-Control-Allow-Origin' : '*',
        'Content-Length' : body.length,
        'Content-Type' : 'text/html'

    });
    res.write(body);
    res.end();

}

function respondFailure(){

    body = "Failure!";
    res.writeHead(200, {

        'Content-Length' : body.length,
        'Content-Type' : 'text/html'

    });
    res.write(body);
    res.end();

}

但是,如果 Web 浏览器没有检测到与源匹配的“Access-Control-Allow-Origin”标头,它似乎会完全避免发送请求。

如何在 Node.js 中向浏览器公开 CORS“Access-Control-Allow-Origin”值?

【问题讨论】:

  • 它像往常一样作为标头发送。是什么让您认为该请求被避免了?不过,应该有一个预检请求。
  • @Bergi 如果浏览器抛出 no "Access-Control-Allow-Origin" 标头错误,请求的处理似乎永远不会启动。
  • @epascarello 这无疑是一篇令人兴奋的文章……

标签: javascript node.js cors


【解决方案1】:

这个问题已经出现过很多次了,但也许值得强调

  1. 对于非简单查询,浏览器会发送一个 OPTIONS 消息预检,如here 所述,并专门询问in this question。您的应用未响应浏览器发送的 OPTIONS 消息,因此随后未启用 CORS。
  2. 具体如何在 node.js 服务器的上下文中拦截 OPTIONS 消息,请参阅 herehere
  3. 此外,当使用 jQuery 访问您的站点时,您需要 construct the headers,如果您正在处理 HTTP Auth,那么您需要 can not accept '*'。看来您正在处理登录类型动词。

【讨论】:

    猜你喜欢
    • 2019-02-07
    • 2016-09-30
    • 1970-01-01
    • 2019-08-29
    • 2018-03-05
    • 2016-09-20
    • 2018-09-19
    • 2019-06-19
    • 2013-08-02
    相关资源
    最近更新 更多