ReactJS在服务器端渲染时使用cookie [英] ReactJS using cookie while rendering on server side
问题描述
我正在开发一个网络应用程序,我使用这个入门工具包作为基础我的项目.问题是 cookie 在服务器端不可用,所以我不能用它来渲染服务器中的组件.
I am working on a web application and I used this starter kit as base of my project. The problem is that the cookie is not available in server side so I cannot use it for rendering a component in server.
我使用react-cookie来保存登录后的账户数据
I use react-cookie to save the account data after login
cookie.save('account', accountData)
并检索
var account = cookie.load('account')
在我需要的时候.我看到 cookie 被保存到浏览器中,我可以在加载组件后在客户端使用它,但我需要它在服务器端进行预渲染操作.
it when I need it. I see that the cookie is saved into browser and I can use it in client side after the component is loaded but I need it in server side for pre-rendering operations.
那么问题是如何做到这一点?或者,如果 cookie 不是正确的方法,那么最好的方法是什么?
So the question is how to achive that? Or, if cookie is not the right approach, what is the best way to do it?
推荐答案
您是否在使用 cookie-parser
中间件?来自 react-cookie
文档:
Are you using the cookie-parser
middleware? From the react-cookie
docs:
您也可以通过在 renderToString 之前添加直接插入 Node.js 请求:
You can also plug it directly with a Node.js request by adding just before the renderToString:
reactCookie.plugToRequest(req, res);
(需要 cookieParser 中间件)
除非您在 Express 应用中安装并启用了一些 cookie 解析中间件,否则 Express 不会解析请求以获取 cookie.
Express won't parse requests to get the cookie out unless you have some cookie parsing middleware installed and enabled in your Express app.
这篇关于ReactJS在服务器端渲染时使用cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!