[英]Express and React, send CSURF token
I have a NodeJs server running some app using EJS, now I want to add a React app.我有一个使用 EJS 运行一些应用程序的 NodeJs 服务器,现在我想添加一个 React 应用程序。
But I don't quite manage to send the csrf token back to the server from React.但我不太设法将 csrf 令牌从 React 发送回服务器。
Here's my server setup:这是我的服务器设置:
const csrfMiddleware = csurf({
cookie: true,
});
app.use(csrfMiddleware);
Here I'm trying to send it from the frontend:在这里,我试图从前端发送它:
let _csrf = cookie.load("_csrf");
const config = {
headers: {
"CSRF-Token": _csrf,
"Content-Type": "application/json",
},
};
But this doesn't work, I get ForbiddenError: invalid csrf token
.但这不起作用,我得到ForbiddenError: invalid csrf token
。 How am I supposed to get the csrf without breaking the current server functionality?我应该如何在不破坏当前服务器功能的情况下获取 csrf?
Thanks in advance提前致谢
I tried figuring it out myself, don't know if it's the best option (probably not), but this is what worked for me.我试着自己弄清楚,不知道这是否是最好的选择(可能不是),但这对我有用。
server:服务器:
app.get("/getcsrf", (req, res) => {
res.json({ _csrf: req.csrfToken() });
});
React:反应:
const { data: csrfData } = await axios.get("/api/campaign/getcsrf");
What I did was, add a route on the server, to get the generated csrf token.我所做的是,在服务器上添加一个路由,以获取生成的 csrf 令牌。
and fetch it on the client-side when needed.并在需要时在客户端获取它。
2 problems: 2个问题:
but at least it works但至少它有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.