我是 javascript 新手,想知道我的代码是否可以接受:我正在使用表达来响应 PUT 请求。我的目标是将更新后的 Sequelize 模型作为响应发送回来,然后将用户重定向回本地 /
。
是否允许使用单独的 return 语句链接两个 .then()
方法?
我显示的代码位于 controller.js
内的回调函数内。
if(!errors.isEmpty()) {
return res.status(404).json({ errors: errors.array() });
} else {
Modules.find({
where: { id: req.params.id }
})
.then(Modules => {
return Modules.updateAttributes({
type: req.body.type,
course: req.body.course,
start: req.body.start,
end: req.body.end,
instructor: req.body.instructor
})
})
.then(updatedModule => {
return res.status(204).json(updatedModule);
})
.then(() => {
return res.redirect(301, "/");
})
.catch(() => {
return res.status(500).json({ errors: errors.array() });
});
}
最佳答案
因此,您想将一些响应发送回用户,然后将其重定向回 baseUrl。
但是很抱歉,这是不可能的,因为当您将 res 发送回客户端时, header 也会随之发送,并且在您使用 res.redirect
后,它会给您一个错误。
您可以在这里做的是直接使用 200 status code
像这样重定向用户
res.status(200)
res.redirect('/')
或者
res.redirect(200, '/')
如果您使用 XHR/AJAX 发送请求,您可以直接根据那里的状态代码编写重定向代码。
关于express - 链接多个响应以发送数据然后重定向 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57439030/