gpt4 book ai didi

javascript - CORS "Access-Control-Allow-Origin"值是如何暴露给浏览器的?

转载 作者:行者123 更新时间:2023-11-30 12:40:14 25 4
gpt4 key购买 nike

在 Node.js 中,我理解在响应 header 中发送“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”header取决于用户名未定义的结果。

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” header ,它似乎会完全避免发送请求。

CORS“Access-Control-Allow-Origin”值如何在 Node.js 中暴露给浏览器?

最佳答案

这个问题多次出现,但也许值得强调

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

关于javascript - CORS "Access-Control-Allow-Origin"值是如何暴露给浏览器的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24727520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com