gpt4 book ai didi

javascript - Express + React : CSRF Cookie is undefined in production, 在本地工作

转载 作者:行者123 更新时间:2023-11-30 10:57:54 25 4
gpt4 key购买 nike

我在 Heroku 上托管我的快速 API,在 Netlify 上托管我的客户端。当我在本地尝试我的注册路由时,我的 cookie 已定义且路由有效。但是,当它投入生产时,cookie 总是返回 undefined 并且我的 API 超时。

请注意,cookie 正在从后端成功发送。我可以在开发工具中查看它。此外,cookies,get() 返回一个空对象。

我正在使用 Js-cookie。

我在 Gatsby 中使用 js-cookie。我在 express 中使用 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,
})
}
}

最佳答案

如果前端和服务器域不同,cookie 将不起作用。

您可以 set up a proxy through Netlify将前端域的所有请求重定向到后端域的路径(例如 /api/ )。

要设置代理,您可以创建一个 _redirects发布目录中的文件(例如 public )具有以下配置:

/api/*  https://<server-url>:<server-port>/:splat 200

最后,将所有 HTTP 请求发送到该前端路径(例如 https://<front-end-url>/api/users)而不是后端 URL,以确保 cookie 正常工作。

关于javascript - Express + React : CSRF Cookie is undefined in production, 在本地工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59258909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com