简体   繁体   English

NodeJS里面的'res没有定义'

[英]Nodejs 'res is not defined' inside require

For my api I want to require a separate file to set a cookie (using cookie-parser). 对于我的api,我需要一个单独的文件来设置cookie(使用cookie-parser)。 However res or req are not passed to the required file... 但是resreq不会传递到所需的文件...

index.js index.js

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

set/cookie.js 集/ 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. 如您所见,部分解决了这个问题,我设置了urlUsername But surely there has to be another way :) ? 但是肯定有另一种方法:)?

Thanks 谢谢

you need to modify your code like this 您需要像这样修改代码

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

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

=========== index.js =========== =========== 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 您需要修改cookie.js文件,以便它创建一个具有缓存功能的对象,并且可以将“ res”对象传递给它,以便在范围内可用

For instance, your cookie.js should look like the following: 例如,您的cookie.js应该如下所示:

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();
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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