错误:Route.post() 需要回调函数,但得到了 [object Object]

Posted

技术标签:

【中文标题】错误:Route.post() 需要回调函数,但得到了 [object Object]【英文标题】:Error: Route.post() requires a callback function but got a [object Object] 【发布时间】:2020-12-20 09:43:23 【问题描述】:

我正在尝试在我的网络应用程序中实现密码重置功能,但标题中不断出现错误。我的代码:

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) => 
    )
    )
    

有效密码token.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 );
    );
;

我的堆栈跟踪:

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

最初代码在路由器第二个参数中没有函数包装,但我添加了它,从那时起访问它时找不到 URL...

【问题讨论】:

我在您的代码示例中没有看到使用中间件的路由 (?)。 @html_programmer 即 router.post('/req-reset-password', function (req, res) ResetPassWord ); 使用 ResetPassword 包装器的用途是什么?另请注意,实际上并未调用包装器中的函数。 尝试解决这个问题。我找到了一个关于 SO 建议这样做的答案。 【参考方案1】:

你可以试试:

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

这应该调用方法ResetPassword。 请注意:正确使用resetPassword 的驼峰式大小写。

编辑:

您的导入可能有问题。 试试

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

或者用大括号导入:

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

编辑 2:

由于使用的是nodejs,所以可以使用es6。

在依赖模块中:

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

在路由器文件中:

import  restPassword  from './controller/resetpassword';

应该可以,我一直都在用。

【讨论】:

然后我得到与标题相同的错误。以及问题中包含的堆栈跟踪 现在我收到Error: Route.post() requires a callback function but got a [object Undefined] :/ SyntaxError: Unexpected token 'export' ... :/ 根据***.com/a/40021867/12360035 不直接支持ES6语法 然后我又得到Error: Route.post() requires a callback function but got a [object Undefined]..

以上是关于错误:Route.post() 需要回调函数,但得到了 [object Object]的主要内容,如果未能解决你的问题,请参考以下文章

laravel 路由回调返回控制器

捕获回调函数引发的错误

错误:Route.get() 需要回调函数,但在 app.js 中获得了 [object Undefined]

在Laravel中提交POST表单后出现302错误

express 中导入变量的问题,错误:Route.get() 需要回调函数

Laravel用post提交表单常见的两个错误