[英]Not able to set cookie from the express app hosted on Heroku
[英]Localhost react app not receiving cookie from Heroku hosted node API
我可以通过 heroku 托管节点 API 使用 POSTMAN 登录和注销。 In my react application, the API call with AXIOS (withcredentials:true) does not set the passport cookies, causing the session to not persist. 本地主机反应和本地主机服务器没有这个问题。
HEROKU 服务器端,我有以下代码:
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解析器在session之上,session在护照之前被初始化。
我的 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);
}
}
});
查了headers,看到发送了cookies但是过滤掉了,来到了一篇文章: heroku博客
2019 年之后,Chrome 等浏览器禁用了跨域 cookies 以防止 CSRF 攻击。
在我的用例中,我可以在节点 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 将您的 cookies 设置为跨域。
在我的情况下,它只是设置,在 session 设置中, cookie.sameSite
为"none"
, proxy
为true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.