我的控制台显示以下错误:
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项目,当一个POST请求到相关的路由处理所产生的误差火灾的容器内工作。
该方法在这里称为:
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);
});
你已经将它定义为一个实例方法:
UserAccount.prototype.setJwTokenCookie
而是要求其作为一个类的方法:
models.UserAccount.setJwTokenCookie
它应该只是:
.then(userRecord => {
const { userId } = userRecord;
return userRecord.setJwTokenCookie(res, userId);
});