ReactJS using cookie while rendering on server side

廉价感情. 提交于 2019-12-22 06:58:13

问题


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.

I use react-cookie to save the account data after login

cookie.save('account', accountData)

and retrieve

var account = cookie.load('account')

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.

So the question is how to achive that? Or, if cookie is not the right approach, what is the best way to do it?


回答1:


Are you using the cookie-parser middleware? From the react-cookie docs:

You can also plug it directly with a Node.js request by adding just before the renderToString:

reactCookie.plugToRequest(req, res);

(require the cookieParser middleware)

Express won't parse requests to get the cookie out unless you have some cookie parsing middleware installed and enabled in your Express app.



来源:https://stackoverflow.com/questions/34525483/reactjs-using-cookie-while-rendering-on-server-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!