简体   繁体   中英

Nodejs 'res is not defined' inside require

For my api I want to require a separate file to set a cookie (using cookie-parser). However res or req are not passed to the required file...

index.js

 app.get('/api/user/:username', function(req, res) {   
 urlUsername = req.params.username;
 require('./set/cookie')
  }); 

set/cookie.js

res.cookie('login_session', urlUsername) // returns 'res' not defined 

As you can see to partially overcome this problem I set urlUsername which works. But surely there has to be another way :) ?

Thanks

you need to modify your code like this

======= set/cookie.js ==========

module.exports = function(res) { // accept res parameter
  res.cookie('login_session', urlUsername)
};

=========== index.js ===========

app.get('/api/user/:username', function(req, res) {   
  urlUsername = req.params.username;
  require('./set/cookie')(res); // pass res to module
}); 

您需要在根据需要创建的模块中使用“ module.exports ”,以返回具有相同名称的对象。

You need to modify your cookie.js file so that it creates an object that has the ability to cache, and that you can pass 'res' object to, so that it is available in scope

For instance, your cookie.js should look like the following:

module.exports.cookie = function(res){
    return {
        cache: function(){
            /*your cookie code*/
            return res.cookie('login_session', urlUsername);
        }
    };
}

This returns an object that has a cache method, and that has the response object passed to it. You would then invoke this by calling:

app.get('/api/user/:username', function(req, res) {   
    urlUsername = req.params.username;
    var cookie = require('./set/cookie').cookie(res);
    cookie.cache();
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM