我目前正在设计一个oauth登录系统,我遇到了以下问题。我试图在用户登录并设置会话数据后将其重定向回主页,但是
res.redirect('/')
投掷
NodeError: Cannot set headers after they are sent to the client
1.我似乎无法让它发挥作用。以下是导致故障的代码:
app.post(
"/auth/openid/return",
passport.authenticate("azuread-openidconnect", {
failureRedirect: "/login"
}),
function(req, res) {
let userProperties = req.user;
new Promise((resolve, reject) => {
MongoClient.connect(url, function(err, db) {
if (err) next(err);
let dbo = db.db("Lektier");
let query = {
oid: req.user.oid
};
dbo.collection("users").findOne(query, function(err, result) {
db.close();
if (result) {
let type = result.type;
resolve(type);
}
});
});
}).then(type => {
req.session.regenerate(function() {
req.session.user = userProperties.upn;
if (type == "teacher") {
req.session.teacheruser = userProperties.upn;
}
let names = userProperties.displayName.toString().split(" ");
req.session.FirstName = names[0];
req.session.LastName = names[1];
res.redirect("/");
});
});
}
);
每当你看到这样的信息
Cannot set headers after they are sent to the client
,这意味着端点的逻辑试图向客户端发送响应,但失败了,因为
它实际上已经做出了回应
.
res.redirect()
of express实际上会向客户端发送一些3xx http状态,如果你说这个方法抛出了你所面临的错误,那么在它已经发送响应之前。