见过很多类似的问题,但无法弄清楚如何解决它。我有一个明确的服务器,使用Cookie的会话。服务器调用谷歌AUTH API
因为它是用于多用户应用程序,我具有对谷歌的认证信息关联到用户ssession
我让他们从谷歌回来后保存在session这些权威性的数据。这些数据以及保存在会话。没有发出这里
但重定向到另一个快递路线之后,会话是不同的,因此,不能访问所保存的数据。
这里是代码
THKS
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安装--save 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
});