本地主机反应应用程序未从 Heroku 托管节点 API 接收 cookie

时间:2021-02-26 01:18:28

标签: node.js reactjs heroku cookies

我可以通过 heroku 托管节点 API 使用 POSTMAN 登录和注销。 在我的 React 应用程序中,使用 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 而不是本地主机吗?

反应方:

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

1 个答案:

答案 0 :(得分:0)

查看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。