【发布时间】:2020-04-03 03:34:04
【问题描述】:
我将我的 express API 托管在 Heroku 上,并将我的 客户端托管在 Netlify 上。当我在本地尝试我的注册路线时,我的 cookie 被定义并且该路线有效。但是,当它在生产中时,cookie 总是返回 undefined 并且我的 API 超时。
请注意,cookie 正在从后端成功发送。我可以在开发工具中查看它。此外,cookies,get() 返回一个空对象。
我正在使用 Js-cookie。
我在 Gatsby 中使用 js-cookie。我正在使用 CSURF 来表达 cookie。
后端:
//CSURF Config
app.use(csurf({ cookie: true }));
//Route that generates CSRF Cookie
app.get("/getToken", (req, res) => {
res.cookie("XSRF-TOKEN", req.csrfToken());
res.end();
});
前端:
我包含了整个注册功能。请注意,这是两个端点调用,一个用于检索 cookie,另一个用于创建用户记录。
userSignUp = async (email, password, resetForm) => {
console.log("THis is a test of the emergency..")
await fetch(process.env.API + "getToken", {
mode: "cors", // no-cors, cors, *include
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "include", // include, *include, omit
headers: {
"content-type": "application/json",
},
method: "GET",
})
const token = Cookies.get("XSRF-TOKEN")
alert(Cookies.get("XSRF-TOKEN"))
const data = await fetch(process.env.API + "signUp", {
body: JSON.stringify({ email: email, password: password }),
mode: "cors", // no-cors, cors, *include
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "include", // include, *include, omit
headers: {
"content-type": "application/json",
"csrf-token": token,
},
method: "POST",
}).catch(error => this.setState({ isError: true }))
if (data.ok) {
console.log(data.ok)
data.json().then(content => {
console.log(content)
this.props.changeAuth(content.authStatus)
this.props.setCategories(content.user.categories)
this.props.getEvents(content.user.events)
resetForm()
})
} else {
this.setState({
isError: true,
})
}
}
【问题讨论】:
-
你的网页网址是什么,你的服务器网址是什么?
-
它们是不同的......一个是heroku随机url,另一个是netlify url注意它在本地主机端口3000(服务器)和本地主机端口8000(客户端)上工作。而且cookies是由服务器设置的。我可以在 chrome 开发工具中看到它们。
标签: javascript reactjs express cookies