[英]Node JS + Express JS: refresh page from other location
I have the following problem: I want to change one variable on a page.我有以下问题:我想更改页面上的一个变量。 The input comes from another page so:
输入来自另一个页面,因此:
I'm using Node.js, Express.js and Ejs for this task.我正在使用 Node.js、Express.js 和 Ejs 来完成这项任务。
I'm sending the variable with fetch post to the server.我将带有 fetch post 的变量发送到服务器。 On the server I change the variable with the request body value and when I reload the "Display page" manually I see the new value.
在服务器上,我使用请求正文值更改变量,当我手动重新加载“显示页面”时,我会看到新值。 The problem is: I need to change it without any manual refresh or other things, because that won't be possible.
问题是:我需要在没有任何手动刷新或其他事情的情况下更改它,因为这是不可能的。
There is the possibility with "location.reload()" to refresh it every X second. “location.reload()”有可能每 X 秒刷新一次。 But that's not the way I want to use, I really just want to refresh it when the variable changes.
但这不是我想使用的方式,我真的只想在变量更改时刷新它。 Is there a function (from express.js for example) I can use for it?
是否有我可以使用的函数(例如来自 express.js)?
edit: I should mention that this project would be just used in our network and its not open for other users.编辑:我应该提到这个项目只会在我们的网络中使用,它不会对其他用户开放。 Like an in-house company dashboard kind of.
就像内部公司仪表板一样。 So a "quick and dirty" solution can work too, but I want to learn something and wanted to do it the right way though.
所以“快速而肮脏”的解决方案也可以工作,但我想学习一些东西,并想以正确的方式去做。
The simplest solution that came to mind is to have the server return the updated post in the body, then use that to update the page.想到的最简单的解决方案是让服务器返回正文中更新的帖子,然后使用它来更新页面。
You can also read about long/short polling and Websockets.您还可以阅读有关长/短轮询和 Websockets 的信息。
This is a very common scenario that has several solutions:这是一个非常常见的场景,有几种解决方案:
One possible solution would be to add page reload code after a successful post-operation with fetch.一种可能的解决方案是在成功执行 fetch 后操作后添加页面重新加载代码。
fetch(url, {
method: 'post',
body: body
}).then(function(response) {
return response.json();
}).then((data) => {
// refresh page here
window.location.replace(url);
});
Proper solution (WebSockets):正确的解决方案(WebSockets):
Outdated (Polling):过时(轮询):
Add express endpoint route: 'variable-state' Call server from your添加快速端点路由:'variable-state' 从您的呼叫服务器
client every n ms and check whether variable state is changed.客户端每 n ms 并检查变量状态是否已更改。
Refresh the page if variable is changed.如果变量更改,请刷新页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.