简体   繁体   English

无法从 Express JS session 在勇敢、firefox 等浏览器以及 chrome 和 edge 中设置 cookie,cookie 无法按预期工作

[英]Unable to set cookie from Express JS session in brave, firefox, etc browsers and in chrome, and edge, cookie isn't working as expected

I have created a website in which I'm facing three issues :我创建了一个网站,其中我面临三个问题

My backend Express JS code:我的后端 Express JS 代码:

index.js file index.js文件

/* eslint-disable no-undef */
const express = require("express");
const cors = require("cors");
const passport = require("passport");
const session = require("express-session");
require("dotenv").config();

// App initialization
const app = express();

const PORT = process.env.PORT || 5000;

// Database connection
require("./db/index").connect();

// Middlewares
app.use(express.json());

// CORS
app.use(
    cors({
        origin: [process.env.FRONTEND_URL, "http://localhost:3000"],
        methods: ["GET", "POST", "PATCH", "DELETE"],
        credentials: true,
    })
);

// Session
app.use(
    session({
        secret: process.env.SESSION_SECRET,
        resave: !process.env.NODE_ENV === "production",
        saveUninitialized: !process.env.NODE_ENV === "production",
        cookie: {
            maxAge: 1000 * 60 * 60 * 24 * 15,
            sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
            secure: process.env.NODE_ENV === "production",
        },
    })
);

if (app.get("env") === "production") {
    app.set("trust proxy", 1); //necessary to set up a cookie in production
}

// Passport
app.use(passport.initialize());
app.use(passport.session());
require("./config/passportConfig")(passport);

// Routes

app.use("/", (_req, res) => {
    res.send("<h1>Welcome to the API :)</h1>");
});

// Listen on port
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

In the front end (React JS) , I'm calling API using Axios like below:前端(React JS)中,我使用 Axios 调用 API,如下所示:

axios.js file axios.js文件

import axios from "axios";

axios.defaults.withCredentials = true;

const customAxios = axios.create({
  baseURL: "https://my-expense-tracker-backend.herokuapp.com",
  timeout: 10000,
});

const requestHandler = (request) => request;

const responseHandler = (response) => {
  return response;
};

const errorHandler = (error) => {
  if (error.response.status === 401) window.location = "/login";
  else if (error.response.status === 0) alert("Server is not running");
  return Promise.reject(error);
};

customAxios.interceptors.request.use(
   (request) => requestHandler(request),
   (error) => errorHandler(error)
);

customAxios.interceptors.response.use(
   (response) => responseHandler(response),
   (error) => errorHandler(error)
);

export default customAxios;

Issues:问题:

  1. Unable to set cookies in some browsers like brave, firefox.无法在某些浏览器中设置 cookies,如勇敢、firefox。 But cookies are working fine in chrome and edge browser.但是 cookies 在 chrome 和 edge 浏览器中运行良好。

  2. When I'm logging in to chrome, edge browser, I'm unable to see any cookie but the app is working fine当我登录到 chrome、edge 浏览器时,我看不到任何 cookie,但应用程序运行正常

    chrome浏览器示例

  3. When I'm logging in the first time, it's working fine in chrome, and the edge browser, but when I'm trying to log in again after 3 to 4 hours, I'm unable to log in automatically even after setting the cookie for 15 days, I have to login again.当我第一次登录时,它在 chrome 和边缘浏览器中运行良好,但是当我在 3 到 4 小时后尝试再次登录时,即使设置了 cookie,我也无法自动登录15天,我必须重新登录。

Can someone help with the above problems?有人可以帮助解决上述问题吗?

Live Website直播网站

Frontend Github link前端 Github 链接

Backend Github link后端 Github 链接

For number 1, I guess there is a bit of difference in browsers behaviour while setting sameSite flag.对于数字 1,我想在设置 sameSite 标志时浏览器的行为会有所不同。 Got this From here 从这里得到这个

Note: Standards related to the Cookie SameSite attribute recently changed such that:注意:与 Cookie SameSite 属性相关的标准最近发生了变化,例如:

The cookie-sending behavior if SameSite is not specified is SameSite=Lax.如果未指定 SameSite,则 cookie 发送行为是 SameSite=Lax。 Previously the default was that cookies were sent for all requests.以前的默认设置是为所有请求发送 cookies。 Cookies with SameSite=None must now also specify the Secure attribute (they require a secure context/HTTPS).带有 SameSite=None 的 Cookies 现在还必须指定安全属性(它们需要安全上下文/HTTPS)。 Cookies from the same domain are no longer considered to be from the same site if sent using a different scheme (http: or https:).如果使用不同的方案(http: 或 https:) 发送,来自同一域的 Cookies 将不再被视为来自同一站点。

For number 2, probably the origin(url) of the cookie(may be from a backend that's on a different url) is different in this case may be from localhost:3000, remember the cookie will be listed from the origin...so if u crank open a new tab and open up the cookies origin url(may be your back end service) and check cookies u should see the cookie there..对于数字 2,可能 cookie 的来源(url)(可能来自不同 url 上的后端)在这种情况下可能来自 localhost:3000,请记住 cookie 将从来源列出......所以如果你打开一个新标签并打开 cookies 原始 URL(可能是你的后端服务)并检查 cookies 你应该在那里看到 cookie。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM