我想在删除用户后显示消息,但我不知道该怎么做。我尝试创建req.session属性然后使用它们但它们在GET路由中不可用。你知道如何修复这段代码吗?
router.get("/", mid.isExpired, mid.isLoggedIn, mid.isAdmin, (req, res) => {
let currentMessage = req.session.message;
let currentState = req.session.state;
req.session.message = undefined;
req.session.state = undefined;
console.log(currentState, currentMessage); //undefined
user.getAll()
.then(result => {
res.render("users", {
name: req.user,
users: result,
msg: currentMessage,
state: currentState
})
})
});
// delete route
router.delete("/delete/:id", mid.isExpired, mid.isLoggedIn, mid.isAdmin, (req, res) => {
user.del(req.params.id)
.then(() => {
req.session.message = "Some message!"
req.session.state = true;
})
});
// jquery
function ajaxDelete(ev, url) {
ev.preventDefault();
$.ajax({
url: url,
type: "DELETE"
});
}
delBtn.click(function(e) {
var user = $(this).data("user");
ajaxDelete(e, "/users/delete/" + user);
window.location.href = "/users";
})

答案 0 :(得分:2)
使用res参数,并创建一个名为message
的变量HttpHeaders
然后
const message= 'MyMessage';
输出
res.json ({message}) // es6 feature
答案 1 :(得分:1)
在您的场景中,据我所知,您希望发送JSON作为响应。您可以使用此代码
router.delete("/delete/:id", mid.isExpired, mid.isLoggedIn, mid.isAdmin, (req, res) => {
user.del(req.params.id)
.then(() => {
var response = { message : "Some message!",
state : true };
return res.json(response);
})
});
关键字'返回'根据您的要求
答案 2 :(得分:0)
路由器和会话是任何nodeJs App的中间件,如果路由器在会话之前添加如下:
app.use(router)
app.use(session(...));
然后会话中间件不会被路由器处理的任何请求调用。 因此改变添加路由器和会话中间件的顺序,如此
app.use(session(...));
app.use(router)