【发布时间】:2021-12-31 19:08:19
【问题描述】:
我正在使用带有 Sequelize 的 Koa 路由器。而且我使用了Sequelize init,其中模型的创建方式如下:
module.exports = (sequelize, DataTypes) => {
class User extends Model {
static associate(models) {
// Associations...
}
}
User.init(
{
email: {
type: DataTypes.STRING,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
},
{
sequelize,
modelName: 'User',
timestamps: false,
}
);
return User;
};
而 koa-router 有:
router.get('/:id', UserController.get);
中间件有:
const db = require('../../../models/index');
module.exports = () => async (ctx, next) => {
try {
ctx.db = db;
next();
} catch (err) {
console.error(err);
ctx.status = 500;
}
};
现在,我有以下代码:
UserController.get = async (ctx) => {
try {
const user = await ctx.db.User.findOne({
where: { id: ctx.params.id });
if (user) {
ctx.body = user;
ctx.status = 200;
} else {
ctx.status = 404;
}
} catch (error) {
ctx.status = 500;
}
};
当我单步调试调试器时,我看到当调试器移至 if (user) { 行时,此 GET 请求的响应返回为 404,即使函数 UserController.get 尚未完成。
任何想法为什么会这样?
【问题讨论】:
标签: node.js sequelize.js koa koa-router