简体   繁体   中英

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

I am trying to implement a password reset functionality into my web app and I keep getting the error in the title. My code:

main.js:

const router = express.Router();
const AsyncNewPassword = require('./controller/asyncnewpassword');
const ResetPassWord = require ('./controller/resetpassword');
const ValidPasswordToken = require ('./controller/validpasswordtoken');
...
router.post('/req-reset-password', function (req, res) { ResetPassWord });
router.post('/new-password', function (req, res) { AsyncNewPassword });
router.post('/valid-password-token', function (req, res) { ValidPasswordToken });

asyncnewpassword.js:

module.exports.NewPassword = async function NewPassword(req, res) {
    passwordResetToken.findOne({ resettoken: req.body.resettoken }, function (err, userToken, next) {
      if (!userToken) {
        return res
          .status(409)
          .json({ message: 'Token has expired' });
      }

      User.findOne({
        _id: userToken._userId
      }, function (err, userEmail, next) {
        if (!userEmail) {
          return res
            .status(409)
            .json({ message: 'User does not exist' });
        }
        return bcrypt.hash(req.body.newPassword, 10, (err, hash) => {
          if (err) {
            return res
              .status(400)
              .json({ message: 'Error hashing password' });
          }
          userEmail.password = hash;
          userEmail.save(function (err) {
            if (err) {
              return res
                .status(400)
                .json({ message: 'Password can not reset.' });
            } else {
              userToken.remove();
              return res
                .status(201)
                .json({ message: 'Password reset successfully' });
            }

          });
        });
      });

    })
}

resetpassword.js:

module.exports.ResetPassword = async function ResetPassword(req, res) {
    if (!req.body.email) {
    return res
    .status(500)
    .json({ message: 'Email is required' });
    }
    const user = await User.findOne({
    email:req.body.email
    });
    if (!user) {
    return res
    .status(409)
    .json({ message: 'Email does not exist' });
    }
    var resettoken = new passwordResetToken({ _userId: user._id, resettoken: crypto.randomBytes(16).toString('hex') });
    resettoken.save(function (err) {
    if (err) { return res.status(500).send({ msg: err.message }); }
    passwordResetToken.find({ _userId: user._id, resettoken: { $ne: resettoken.resettoken } }).remove().exec();
    res.status(200).json({ message: 'Reset Password successfully.' });
    var transporter = nodemailer.createTransport({
      service: 'Gmail',
      port: 465,
      auth: {
        user: 'user',
        pass: 'password'
      }
    });
    var mailOptions = {
    to: user.email,
    from: 'bot@example.com',
    subject: 'Node.js Password Reset',
    text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
    'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
    'http://localhost:4200/response-reset-password/' + resettoken.resettoken + '\n\n' +
    'If you did not request this, please ignore this email and your password will remain unchanged.\n'
    }
    transporter.sendMail(mailOptions, (err, info) => {
    })
    })
    }

validpasswordtoken.js:

module.exports.ValidPasswordToken = async function ValidPasswordToken(req, res) {
    if (!req.body.resettoken) {
    return res
    .status(500)
    .json({ message: 'Token is required' });
    }
    const user = await passwordResetToken.findOne({
    resettoken: req.body.resettoken
    });
    if (!user) {
    return res
    .status(409)
    .json({ message: 'Invalid URL' });
    }
    User.findOneAndUpdate({ _id: user._userId }).then(() => {
    res.status(200).json({ message: 'Token verified successfully.' });
    }).catch((err) => {
    return res.status(500).send({ msg: err.message });
    });
};

My stack trace:

Error: Route.post() requires a callback function but got a [object Object]
    at Route.<computed> [as post] (C:\Apps\Projects\Project1\backend\node_modules\express\lib\router\route.js:202:15)
    at Function.proto.<computed> [as post] (C:\Apps\Projects\Project1\backend\node_modules\express\lib\router\index.js:510:19)
    at Object.<anonymous> (C:\Apps\Projects\Project1\backend\index.js:441:8)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

Originally the code had no function wrapper in the router second argument, but I added it and since then the URL would not get found when accessing it...

Can you try:

router.post('/req-reset-password', ResetPassWord);

This should call the method ResetPassword .
Juste a note: correct camel casing with resetPassword .

Edit:

Maybe there is something wrong with your import.
Try

module.exports = async function ResetPassword(req, res) {
... 

Or else import with braces:

const { ResetPassWord } = require ('./controller/resetpassword');

Edit 2:

Since you're using nodejs, you can use es6.

In the dependend module:

exports.resetPassword = async (req, res) => {
... 

In the router file:

import { restPassword } from './controller/resetpassword';

Should work, I use it all the time.

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