Every time React sends request to Express, a new session is generated

别来无恙 提交于 2020-06-27 12:59:05

问题


I use React as a client to send request to Express with proxy and express-session set up. But every time React makes a request to Express server, a new session is created. So I checked Express alone by manually accessing to the same api url and it keep using the same session each time I refresh the page.

Project structure:

project-folder
 - client // React client with proxy set up
      + src
      + package.json
      + ...
 - server.js
 - package.json

Inside 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 });
});

Here is how React client send its request to 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;
}

I think the problem comes from the misconfiguration between React and Express. Did anyone have this problem before?


回答1:


fetch does not send cookie by default, you need to set it explicitly:

fetch(url, {
  method: 'GET',
  credentials: 'include',
  // ...
})


来源:https://stackoverflow.com/questions/48039689/every-time-react-sends-request-to-express-a-new-session-is-generated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!