为什么客户端为每个请求生成一个新的会话ID,而不是返回服务器提供的会话ID?

问题描述 投票:0回答:1

我在 PERN 应用程序中使用 Passport.js,但是当我发出 get 请求时,客户端似乎会为每个请求生成一个新的随机会话 ID。 Passport 配置为处理提供的会话 ID 以验证每个请求,但显然这不起作用,因为每个随机的新会话 ID 无法与数据库会话表中存储的 ID 匹配。

获取请求(前端):

export const welcomeDetails = async () => {
    console.log('welcome details called');
    try {
    const response = await fetch(`${API_ENDPOINT}/welcome`, {
        method: "GET",        
        credentials: 'same-origin',
        mode: 'cors',
        "Access-Control-Allow-Credentials": true,
        headers: {
            "Content-Type": "application/json"            
        }
    })
    if (!response.ok){
      console.log('response was not okay');
      throw new Error('response was not okay');
    }
    console.log('response was okay');
    const data = await response.json()
    console.log(data);
    return data;
  } catch (error){
    console.log(error);
  }

}

Cors配置(后端):

app.use(
  cors({
    origin:
      process.env.NODE_ENV === 'development'
        ? process.env.DEV_ORIGIN
        : process.env.PROD_ORIGIN,
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
  }),
);

会话配置(后端):

app.use(session({
  store: new pgSession ({
    // connect-pg-simple options:
    pool : pgPool,
    tableName : "session"
  }),
  secret: [THE SECRET],
  saveUninitialized: true,
  resave: false,
  cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 } // 30 days
}));

非常感谢您的帮助,谢谢!

reactjs cookies get fetch sessionid
1个回答
0
投票

通常我会在发布问题后立即找到答案。这并不是说一旦用户已经登录,我就必须编辑 get 请求的标头设置,它们必须在用户登录时已经设置。将以下内容添加到登录 POST 请求的标头中现在一切正常了:

        "Access-Control-Allow-Credentials": true,
        "Access-Control-Allow-Origin": true,      
        "Access-Control-Allow-Headers": true, 
        "Access-Control-Allow-Methods": true 

更详细:

const response = await fetch(`${API_ENDPOINT}/login`, {
method: "POST",
body: JSON.stringify({        
    username: email,
    password: password
}),
credentials: 'include',
mode: 'cors',
headers: {
    "Content-Type": "application/json",
    "Access-Control-Allow-Credentials": true,
    "Access-Control-Allow-Origin": true,      
    "Access-Control-Allow-Headers": true, 
    "Access-Control-Allow-Methods": true 
}
© www.soinside.com 2019 - 2024. All rights reserved.