Express CORS域白名单

编程入门 行业动态 更新时间:2024-10-27 00:26:29
本文介绍了Express CORS域白名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用此模块来处理cors请求 www.npmjs/package/cors 我需要限制除白名单之外的所有域

I am using this module to handle cors requests www.npmjs/package/cors I need to restrict all domains except whitelisted

从官方CORS模块示例中:

From official CORS module example:

var whitelist = ['example1', 'example2']; var corsOptions = { origin: function(origin, callback){ var originIsWhitelisted = whitelist.indexOf(origin) !== -1; callback(null, originIsWhitelisted); } }; app.get('/products/:id', cors(corsOptions), function(req, res, next){ res.json({msg: 'This is CORS-enabled for a whitelisted domain.'}); });

为了使它起作用,我对此进行了更改:

Which I have changed to this to make it work:

var origin; var corsOptions; app.all('*', function (req, res, next) { origin = req.get('origin'); var whitelist = ['example1', 'example2']; corsOptions = { origin: function (origin, callback) { var originIsWhitelisted = whitelist.indexOf(origin) !== -1; callback(null, originIsWhitelisted); } }; next(); }); app.post('/products/:id', cors(corsOptions), function (req, res, next) { res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' }); });

然后我从 http:// localhost:8080 通过发布到 app.post('/ products /:id'...)我希望它不应该执行,因为 http :// localhost:8080 不在白名单中,但实际上已经列入白名单。知道为什么以及如何解决这个问题吗?

Then I run test from localhost:8080 by posting to app.post('/products/:id'...) I expected it should not be executed because localhost:8080 is not whitelisted but actually it did. Any idea why and how to fix that?

我也确实添加了 cors(corsOptions)来观看,但这是在说-不可用

Also I didadd cors(corsOptions) to watch but it is saying - not available

推荐答案

原因是 corsOptions 仍为未定义(实际上与 cors()),因为在启动期间会立即评估 cors(corsOptions)。

The reason is that corsOptions is still undefined when cors(corsOptions) is called (effectively the same as cors()) since cors(corsOptions) is evaluated immediately during startup.

更多推荐

Express CORS域白名单

本文发布于:2023-11-27 06:48:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637022.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:名单   Express   CORS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!