[英]Localhost react app not receiving cookie from Heroku hosted node API
I am able to log in and out with POSTMAN through the 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. In my react application, the API call with AXIOS (withcredentials:true) does not set the passport cookies, causing the session to not persist. Localhost react and Localhost server does not have this problem.本地主机反应和本地主机服务器没有这个问题。
HEROKU SERVER SIDE, I have the following code: 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());
I have checked that the cookie parser is above the session, the session is initialized before passport.我检查了cookie解析器在session之上,session在护照之前被初始化。
Is my cors affecting my local reactapp?我的 cors 会影响我本地的 reactapp 吗? instead of localhost, am I supposed to reference my local computer's external API?我应该引用本地计算机的外部 API 而不是 localhost?
REACT SIDE:反应方面:
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);
}
}
});
After checking the headers and seeing that the cookies are sent but filtered out, I came to a article: heroku blog查了headers,看到发送了cookies但是过滤掉了,来到了一篇文章: heroku博客
After 2019, Chrome and other browsers have cross domain cookies disabled to prevent CSRF attacks. 2019 年之后,Chrome 等浏览器禁用了跨域 cookies 以防止 CSRF 攻击。
In my use case, I can just turn it off with the following on the Node API server:在我的用例中,我可以在节点 API 服务器上使用以下命令将其关闭:
app.use(session({
secret: 'street',
resave: true,
saveUninitialized: true,
proxy: true,
cookie: {
sameSite:'none',
secure:true
},
store: new MongoStore({ mongooseConnection: mongoose.connection },)
}));
changing samesite to none, will allow chrome to set your cookies with cross domains.将 samesite 更改为 none,将允许 chrome 将您的 cookies 设置为跨域。
In my case, it was just setting, in the session settings, cookie.sameSite
to "none"
, and proxy
to true
.在我的情况下,它只是设置,在 session 设置中, cookie.sameSite
为"none"
, proxy
为true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.