gpt4 book ai didi

express - 在 Express 中获取请求来源

转载 作者:行者123 更新时间:2023-12-01 23:41:55 25 4
gpt4 key购买 nike

我如何真正获得起源?当我在 router.get('/', ...) 下使用以下内容时,它只是返回未定义。

var origin = req.get('origin');

(我试图使用原始域作为查找键,然后构造正确的 URL 参数以发布到 API)

最佳答案

在请求的路径中添加这个 expressJs 中间件。确保它是第一个遇到的中间件请求。

/**
* Creates origin property on request object
*/
app.use(function (req, _res, next) {
var protocol = req.protocol;

var hostHeaderIndex = req.rawHeaders.indexOf('Host') + 1;
var host = hostHeaderIndex ? req.rawHeaders[hostHeaderIndex] : undefined;

Object.defineProperty(req, 'origin', {
get: function () {
if (!host) {
return req.headers.referer ? req.headers.referer.substring(0, req.headers.referer.length - 1) : undefined;
}
else {
return protocol + '://' + host;
}
}
});

next();
});

其中 app 是 express app 或 express router 对象。

关于express - 在 Express 中获取请求来源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36554375/

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