简体   繁体   English

在node.js中呈现页面之前将数据传递给服务器?

[英]Passing data to server before page is rendered in node.js?

After a user login, the data is stored on a client side. 用户登录后,数据存储在客户端。

There are some pages which don't require a logged user to be viewed... 有些页面不需要查看已登录用户...

for example, I have a route on node.js which render a profile page through a URL parameter. 例如,我在node.js上有一条路由,该路由通过URL参数呈现配置文件页面。

app.get("Profile/:id",function(req,res){ //render page and send it.}

anyone can see this page... but here is the situation... in my app, users can post notes on this pages so they can see it later. 任何人都可以看到此页面...但是这里就是这种情况...在我的应用中,用户可以在此页面上发布注释,以便以后查看。 So the idea is, if a user is logged in when the user access that page he can see all his notes. 因此,想法是,如果用户在访问该页面时登录,则可以看到其所有注释。

the data of the notes are in server side. 注释的数据在服务器端。

So my question is... how can I pass the user data into app.get("profile/:id "... function so that the notes can be loaded and sent when is rendered ... 所以我的问题是...如何将用户数据传递到app.get(“ profile /:id” ...函数中,以便在呈现注释时可以加载和发送注释...

one thing is important to be known. 重要的是要知道一件事。 I have a solution in wich I pass a unique key though the url which references to the active socket of the user so that the data is post on a json, is there any other way to pass data from client to server before the page is rendered? 我有一个解决方案,我通过URL传递唯一键,该URL引用用户的活动套接字,以便将数据发布在json上,还有其他方法可以在呈现页面之前将数据从客户端传递到服务器?

After several days I have manage to achieve the resolution of this question 几天后,我设法解决了这个问题

The idea is to have a Session tipe variable like $_SESSION in php. 这个想法是在php中有一个会话提示变量,如$ _SESSION。

you need express-session npm and assign session on require parameter on a express post function. 您需要express-session npm并在Express post函数上的require参数上分配会话。 After you have set a value, every time that browser change from location, you can extract that same session variable and use the data to post a response when you are rendering. 设置值之后,每次浏览器从位置更改时,都可以提取相同的会话变量,并在渲染时使用数据发布响应。

I used ejs to render. 我用ejs渲染。

In the next link, there is a full tutorial to achieve this. 在下一个链接中,有完整的教程可以实现此目的。

https://codeforgeek.com/2014/09/manage-session-using-node-js-express-4/ https://codeforgeek.com/2014/09/manage-session-using-node-js-express-4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM