已经看到过许多类似的问题,但不知道如何解决。
我有一台使用Cookie会话的快递服务器。服务器正在调用google auth api。
因为它是一个用于多用户的应用程序,所以我必须将google auth信息与用户会话关联
从Google取回它们后,我将这些身份验证数据保存在会话中。
数据保存在会话中。这里没问题
但是在重定向到另一个快速路由后,会话有所不同,因此无法访问已保存的数据。
这是代码
谢谢
app.use(
session({
name: SESSION_NAME,
secret: SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
maxAge: parseInt(SESSION_LIFETIME, 10), // 24H in config file
httpOnly: true,
sameSite: true,
secure: !IN_DEV
}
})
);
googleRouter.get("/oauthcallback", async (req, res) => {
try {
if (req.query.code && req.query.code !== "") {
const oauth2Client = initGoogleAuth();
const tokens = await getGoogleToken(oauth2Client, req.query.code);
if (tokens && tokens !== "") {
const s = await saveTokensInSession(req.session, tokens);
oauth2Client.setCredentials(tokens);
// save data in session
req.session.oauth2Client = oauth2Client;
req.session.save();
// oauth2Client is well saved here in session
console.log(req.session.oauth2Client);
//redirect to the next url
res.redirect("/googleauth/test");
} else res.send("error while getting tokens");
} else res.send("error while getting authorization code");
} catch (error) {
res.send(`error while getting token : ${error}`);
}
});
googleRouter.get("/test", async (req, res) => {
// oauth2Client is empty here and sessionID is different
console.log(req.session.oauth2Client);
});
最佳答案
npm install-保存cors
允许通过cors中间件访问适当的端口
app.use (cors ({
credentials: true,
origin: [
"http: // your domain address",
"http: // yourdomain address: port"
]
}));
尝试通过“保存”功能的回调进行重定向。
req.session.save ((err) => {
// try to redirect within callback function
res.redirect ("/googleauth/test");
})
如果采用邮政方式,请按以下方式更换。
res.redirect (307, "/googleauth/test");
然后在客户端代码中的数据传输模块(例如axios等)的配置中设置withCredentials:true。
const config = {
headers: {'Content-Type': 'application/json'},
withCredentials:true
};
axios.post('http://your domain address:port/route',{},config)
.then( response => {
//response.data your codes
});