简体   繁体   中英

Creating a function and calling it on another file in node.js

I have this checking auth function on my login.js page, inside my routes folder. my dir is set up like so:

routes
    login.js

views
    index.ejs
    login.ejs

app.js

so I have a function inside app.js like this:

app.get('/dashboard', auth, (req, res) => {
     ...

})

the auth function inside the login.js looks like this:

    function auth(res, req, next) {
    if (req.session.loggedin) {
        return next();
    } else {
      req.session.destory;
      res.redirect('/login')
    }
}

module.exports = app

here's how I am requiring the code inside the login page:

var login = require('./routes/login')
app.use(login)

However, when I require the proper file name and everything, it says auth is not recognized. how is this possible? How do I fix this?

In the login.js file, you have written module.exports = app . Instead, You have to write module.exports = auth to send the auth function.

So, when you var login = require('./routes/login') , you get the function auth() from login.js and store the function in the name login in app.js

Therefore, while reffering in app.js , your function is login() and not auth() as you imported it that way.

If you want to use auth in app.js you can do var auth = require('./routes/login');

Otherwise instead of writing app.get('dashboard', auth... you have to write app.get('dashboard', login...

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