节点表达和路由 [英] Node express cors and routes

查看:176
本文介绍了节点表达和路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用CORS https://www.npmjs.com/package/cors 允许 whitedomain 列表。

I am using CORS https://www.npmjs.com/package/cors to allow whitedomain list.

   var whitelist = ['http://example1.com', 'http://example2.com'];
var corsOptions = {
  origin: function(origin, callback){
    var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
    callback(null, originIsWhitelisted);
  }
};

app.post('/products/:id', cors(corsOptions), function (req, res, next) {
    console.log(0);
    res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' });        
});

如果非whitedomain 没有访问控制允许原因这是罚款,但同时我可以看到在调试,行 res.json({ msg:'这是为白名单域启用的CORS。'}); console.log(0); code> console.log(0); c>在服务器端的控制台打印 0 这是我不想

In case of non whitedomain the server returns No 'Access-Control-Allow-Origin' which is fine but at the same time I can see on debug that the lines res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' }); and console.log(0); still gets executed - console.log(0); printed 0 in console on server side which is something I do not wan't in that case.

所以让我们说如果是扭动到数据库:

So lets say if is writhing to database:

app.post('/products/:id', cors(corsOptions), function (req, res, next) {
        writeToDatabase();
        res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' });            
    });

这样 writeToDatabase(); 执行。但是我想避免这种情况,因为在非白名单域中,我不需要在数据库中写任何东西。

This way writeToDatabase(); will always be executed. But I want to avoid that because I do not need to write any stuff in to database in case of non whitelisted domain.

任何想法?

推荐答案

我的想法是使用if来过滤app.post中的请求
例如,

My idea is to use if to filter the request inside the app.post so for example,

app.post('/products/:id', cors(corsOptions), function (req, res, next) {
        if(req.header[origin]===whitelisted){
        writeToDatabase();
        res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' }); }           
    });

这篇关于节点表达和路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆