Express PUT接口函数返回undefined问题求助
解决Express中Knex/Bookshelf PUT接口返回undefined的问题
兄弟,我一眼就瞅出你这个问题的症结了——你的editStatus控制器函数没有返回Promise链!这就是为啥路由里调用它的时候会报错Cannot read property 'then' of undefined,因为函数默认返回undefined,根本没有.then()方法可以调用。
咱们来拆解一下:你在editStatus里执行了new Student({id:id}).save(...),这确实是一个异步的Promise操作,但你没把这个Promise对象return出去,外部调用students.editStatus()的时候自然拿不到异步操作的结果,只能拿到undefined。
修复步骤:
1. 修改控制器代码,返回Promise链
给你的editStatus函数加上return,同时建议加上{patch: true}选项(只更新指定字段,避免覆盖其他未修改的字段),还要把错误抛出去让路由层处理:
exports.editStatus=(id)=>{ console.log(id) const fieldToUpdate={status:'in'} // 关键:返回整个Promise链 return new Student({id:id}) .save(fieldToUpdate, {patch: true}) .then(saved=>{ console.log(saved) return saved; }).catch(err=>{ console.log(err) // 抛出错误,让路由的catch捕获 throw err; }) }
2. 完善路由的错误处理
在路由里加上.catch()分支,这样出错的时候能给前端返回合适的错误信息,而不是直接崩溃:
app.put('/studentList/:id', (req,res)=>{ students.editStatus(req.params.id) .then((student) => { res.send(student.attributes) }) .catch(err => { res.status(500).json({error: err.message || '更新学生状态失败'}) }) })
为什么要加{patch: true}?
Bookshelf的save()方法默认会尝试更新整个模型,如果你的Student模型有其他字段(比如name、age),不加这个选项的话,这些字段会被设为null或者默认值,这显然不是你想要的。加上{patch: true}后,只会更新你指定的status字段,更安全也更符合需求。
现在再测试一下,你会发现student.attributes能正常返回给前端了,之前的undefined问题也解决啦!
内容的提问来源于stack exchange,提问作者Jaime Ivy Arrestinya Pendlebur
相关产品推荐
相关产品推荐

