简体   繁体   中英

how to export function and use it as middleware node.js

in my middleware folder, I have a file called auth.js .

In this file, I have this function:

function authCheck () {
      if (req.session.loggedin) {

          return;

      } else {

          req.session.destory();
          res.redirect('/login')

     }

}

I need to export it, and then use it in my other files, so then I would need to import it inside of my root directory app.js file, and my routes folder, those js files there.

I basically want to do this:

app.get('/index', authCheck, (req, res) => {

 .....
}

how do I do this?

You use app.use assuming you're using expressjs and use next() to continue the execution

auth.js

function authCheck (req, res, next) {
      if (req.session.loggedin) {

          next();

      } else {

          req.session.destory();
          res.redirect('/login')

     }

}
module.exports = { authCheck }

app.js

const {authCheck} = require('./auth.js');

app.use(authCheck)
app.get('/index', (req, res) => {

 .....
}

Node modules is what you're looking for.

Here's an example from the nodejs documentation.

Export a function from addTwo.mjs

// addTwo.mjs
function addTwo(num) {
  return num + 2;
}

export { addTwo };

Import and use the exported function in app.mjs

// app.mjs
import { addTwo } from './addTwo.mjs';

// Prints: 6
console.log(addTwo(4));

Note that the file extension .mjs is used to specify that you're using es6 modules. Read more here.

https://nodejs.org/api/esm.html#esm_introduction

You can create a middleware like auth.js file in it and add auth code in it like below:

module.exports = {
    authCheck: (req, res, next) => {
   }
}

And import that file in your route folder and use it like below:

const auth = require('../middlewares/auth')

router.post("/", auth.authCheck, (req, res, next) => {
      
});

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