Sequelize 4.42.0:设置实例方法将返回“非函数”错误

时间:2019-01-27 21:28:12

标签: node.js express sequelize.js

我的控制台显示以下错误:

POST /log-in 200 637.310 ms - 42
Unhandled rejection TypeError: models.UserAccount.setJwTokenCookie is not a function
    at models.UserAccount.findOne.then.userRecord (/home/owner/PhpstormProjects/reportingAreaApi/routes/index.js:99:33)
    at tryCatcher (/home/owner/PhpstormProjects/reportingAreaApi/node_modules/bluebird/js/release/util.js:16:23)

我一直在尝试将实例方法添加到UserAccount模型定义中。方法setJwTokenCookie似乎在以下地方有误:

'use strict';
require('dotenv').load();
const bcryptjs = require('bcryptjs'),
      jsonWebToken = require('jsonwebtoken'),
      moment = require('moment'); 


module.exports = (sequelize, DataTypes) => {
  const UserAccount = sequelize.define('UserAccount', {
    username: DataTypes.STRING,
    password: DataTypes.STRING
  });

    // cookie-setter
  UserAccount.prototype.setJwTokenCookie = (responseLocal, userId) => {
    // generate a new jwt encoded with userId:
    const signedToken = jsonWebToken.sign({
      data: {
        userId : userId
      }
    }, <secret>); 

    const dateIn10Years = new moment()
      .add(10, "years").toDate();

    responseLocal.cookie('jwTokenCookie', signedToken, {
      httpOnly: true,
      expires : dateIn10Years
    })
  };

  return UserAccount;
};

我正在尝试遵循此处显示的实例方法格式:http://docs.sequelizejs.com/manual/tutorial/models-definition.html#expansion-of-models

有人知道此错误的根源吗?我正在Express.js项目内部工作,并且对相关的路由处理程序发出了发布请求时,将引发错误。

该方法在这里调用:

router.post('/log-in', passport.authenticate('local'), (req, res) => {
  // get the user's Id. Then set the cookie with it
  models.UserAccount.findOne({ where : { username : req.body.username }})
    .then(userRecord => {
      const { userId } = userRecord;
      return models.UserAccount.setJwTokenCookie(res, userId);
    });

1 个答案:

答案 0 :(得分:1)

您已将其定义为实例方法:

UserAccount.prototype.setJwTokenCookie

但是将其作为类方法调用

models.UserAccount.setJwTokenCookie

应该是:

.then(userRecord => {
  const { userId } = userRecord;
  return userRecord.setJwTokenCookie(res, userId);
});