我使用React
作为客户端,在设置Express
和proxy
的情况下向express-session
发送请求。但每次React向Express服务器发出请求时,都会创建一个新会话。所以我通过手动访问相同的api url来单独检查Express,并且每次刷新页面时它都会继续使用相同的会话。
项目结构:
project-folder
- client // React client with proxy set up
+ src
+ package.json
+ ...
- server.js
- package.json
内部server.js
:
const session = require('express-session');
let sessionConf = {
name: 'aoid',
secret: 'stackoverflow',
resave: true,
saveUninitialized: true,
rolling: true,
cookie: {
httpOnly: false,
secure: false,
maxAge: 2000000
}
};
app.use(session(sessionConf));
app.get('/api/prod', (req, res, next) => {
let sessionId = req.sessionID; // is generated each time React client send request, works fine with api alone!
console.log(sessionId);
if (!sessionId) return res.status(401).send('Unauthorized Error');
res.status(200).send({ data });
});
以下是React客户端如何将其请求发送到Express:
let loadItems = async () => {
const response = await fetch('/api/prod');
const body = await response.json();
if (response.status !== 200) throw Error(body.message);
return body;
}
我认为问题来自React和Express之间的错误配置。有人以前有这个问题吗?
答案 0 :(得分:5)
fetch
默认情况下不会发送cookie
,您需要明确设置它:
fetch(url, {
method: 'GET',
credentials: 'include',
// ...
})