Skip to content
Advertisement

How to export function as function expression in express node js

I have a function

exports.loginService = async(req,res) => {
  const { workerId, workerPassword } = req.body;
  try {
    const foundUser = await User.findOne({ workerId });
    if (!foundUser) {
      return res.status(404).json({
        message: "Employee does not exist (Invalid Employee ID)",
      });
    } else if (foundUser.totalLoginAttemptLeft > 0) {
      const { updatedWorker, isMatch } = await checkPassword(
        workerPassword,
        foundUser
      );
      if (!isMatch) {
        passwordNotMatched(res, updatedWorker);
      } else {
        const jwtToken = await totalLogin(foundUser, reset);
        return res.status(200).json({ token: "Bearer " + jwtToken });
      }
    } else {
      return res.status(400).json({
        message: "You'r account is locked Please contact to ADMIN or HR",
      });
    }
  } catch (error) {
    console.error(error.message);
    return res.status(500).json({ message: error.message });
  }
}

I am exporting this in the main route file

const loginService = require("../../services/authServices")

router.post("/login", loginService);

But when I running the code it’s giving this error

Error: Route.post() requires a callback function but got a [object] Object

What I am doing wrong?

Advertisement

Answer

You’re trying to use the exports object as though it were a function. If you want to only export the function, overwrite exports rather than assigning to a property on it:

module.exports = async(req,res) => {
// ...
};

(Note that it has to be module.exports, not just exports.)

Alternatively, keep your current export and destructure the require call:

const { loginService } = require("../../services/authServices");
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement