【问题标题】:Localhost react app not receiving cookie from Heroku hosted node API本地主机反应应用程序未从 Heroku 托管节点 API 接收 cookie
【发布时间】:2021-02-26 01:18:28
【问题描述】:

我可以通过 heroku 托管节点 API 使用 POSTMAN 登录和注销。 在我的反应应用程序中,使用 AXIOS (withcredentials:true) 的 API 调用没有设置护照 cookie,导致会话不持久。本地主机反应,本地主机服务器没有这个问题。

HEROKU SERVER SIDE,我有以下代码:

app.use(cors({
    origin: "http://localhost:3000",
    credentials: true
})); 
app.enable('trust proxy');
mongoose.connect(dbconfig.url, {
    useUnifiedTopology: true,
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false });

// Parse URL-encoded bodies (as sent by HTML forms)
app.use(express.urlencoded({extended: true}));
app.use(cookieParser('street'));
app.use(session({
    secret: 'katsura street',
    resave: true,
    saveUninitialized: true,
    proxy: true,
    store: new MongoStore({ mongooseConnection: mongoose.connection },)
}));
app.use(passport.initialize());
app.use(passport.session());

我检查了 cookie 解析器是否在会话之上, 会话在护照之前初始化。

我的 cors 会影响我本地的 reactapp 吗?我应该引用本地计算机的外部 API 而不是 localhost?

反应方面:

 Axios.post(Config.ServerURL + 'auth/login',
            {email: this.state.email, password: this.state.password},
            {
                withCredentials: true
            }).then(result => {
                console.log(result.data);
        
        }).catch(error => {
            //make sure message doesn't crash
            if (error.response !== undefined) {
                try {
                    console.log(error.response);
                    this.setState({message: error.response.data.info.message})

                }catch(error) {
                    console.log(error);
                }
            }
        });

【问题讨论】:

    标签: node.js reactjs heroku cookies


    【解决方案1】:

    查看了headers,看到cookies发送了但是被过滤掉了,来到了一篇文章:heroku blog

    2019 年之后,Chrome 等浏览器禁用跨域 cookie 以防止 CSRF 攻击。

    在我的用例中,我可以在 Node API 服务器上使用以下命令将其关闭:

    app.use(session({
        secret: 'street',
        resave: true,
        saveUninitialized: true,
        proxy: true,
        cookie: {
            sameSite:'none',
            secure:true
        },
        store: new MongoStore({ mongooseConnection: mongoose.connection },)
    }));
    

    将 samesite 更改为 none,将允许 chrome 使用跨域设置您的 cookie。

    【讨论】:

    • 在 Heroku 上部署 Vue UI 和 Node API 后,我遇到了同样的问题(我认为)。我假设由于他们使用相同的域(herokuapp.com),我相信我正确设置了 CORS,并且我使用的是带有 SSL 的 Heroku 付费版本,Chrome 会发送 cookie。 (我正在使用 JWT 并依赖客户端发回作为 http-only cookie 发送的刷新令牌。)但我没有收到任何 cookie。听起来上面的解决方案会起作用,我只是不知道如何应用它。在我的 Node API 的 server.js 中?我没有在任何地方使用会话。任何提示将不胜感激。
    • 经过 12 小时的努力,proxy:true + samesite:"none" 发挥了作用。太感谢队友了。祝你一切顺利。
    【解决方案2】:

    就我而言,它只是在会话设置中将cookie.sameSite 设置为"none",将proxy 设置为true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-21
      • 2021-03-08
      • 2022-08-04
      • 2019-02-03
      • 2021-10-30
      • 1970-01-01
      相关资源
      最近更新 更多