都会生成一个新会话

都会生成一个新会话

本文介绍了每当React向Express发送请求时,都会生成一个新会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用React作为客户端,以设置proxyexpress-session的方式向Express发送请求.但是,每当React向Express服务器发出请求时,都会创建一个新会话.因此,我通过手动访问相同的api URL单独检查了Express,并且每次刷新页面时它都使用相同的会话.

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-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的方式:

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

我认为问题出在React和Express之间的配置错误.有人遇到过这个问题吗?

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

推荐答案

fetch 默认情况下不发送cookie,您需要对其进行显式设置:

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

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

这篇关于每当React向Express发送请求时,都会生成一个新会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 04:39