Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

express - Importing and Exporting Module Variables - Node.js

I have a route of type post, that is receiving some info from the front-end, as shown below:

const router = require("express").Router();
const UsernameController = require("../controllers/username.controller");

router.post("/username", async (req, res) => {
  try {
    const cookie = req.cookies;
    const {userName} = req.body;
    let allGames = await new UsernameController().getGames(userName);
    console.log(allGames[0].games)
    return res.sendStatus(200)
  } catch (err) {
    console.log(err);
    res.status(422).send(err);
  };
});

module.exports = router;

I need to use the destructured {userName} = req.body in another file. So I’m wondering how I can export the {userName} received from the front-end to the middleware.js file.

middleware.js:

const AuthController = require("../controllers/auth.controller");
const UsernameController = require("../controllers/username.controller");
const usernameRouter = require('../routes/username.route')

module.exports = async (req, res, next) => {
  let userName = usernameRouter.userName
  const userGamesArray = await new  UsernameController().getGames(userName)
  req.userGamesArray = userGamesArray;
  next();
};

When I console.log the userName variable in the middleware file, it responds with undefined which means I’m importing the variable wrongly from the route.js file.

Kindly assist me with importing the variable from the route.js file to the middleware.js file.

question from:https://stackoverflow.com/questions/66061434/importing-and-exporting-module-variables-node-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You just need to use a middleware in this /username route like this:

const middleware = require("./middleware"); // correct this path to a real one

router.post("/username", middleware, async (req, res) => {
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...