[英]How do I refresh browser from server-side with node.js?
I want to reload page when my html files are changed (while development) because of HMR bug in html-webpack-plugin and webpack-dev-middleware (webpack-hot-middleware) interop.由于 html-webpack-plugin 和 webpack-dev-middleware (webpack-hot-middleware) 互操作中的 HMR 错误,我想在我的 html 文件更改(在开发时)时重新加载页面。
Here are two repositories where I got this problem, there are issues in both.这是我遇到此问题的两个存储库,两者都有问题。
How can I reload page using this tools?如何使用此工具重新加载页面?
There are a few ways to refresh a client's browser from the server.有几种方法可以从服务器刷新客户端的浏览器。
Server-Sent Events:服务器发送事件:
One simple method that works across browsers and servers uses server-sent events .一种跨浏览器和服务器工作的简单方法使用服务器发送事件。 The minimal process is:最小的过程是:
var evtSource = new EventSource("<server_URL>/subscribe");
evtSource.onmessage = function () { myPageRefresh() };
On the server side, set up a handler for GET /subscribe
requests and keep track of the subscribed client:在服务器端,为GET /subscribe
请求设置处理程序并跟踪订阅的客户端:
const express = require('express');
const app = express();
var client = null;
app.get('/subscribe', (req, res) => {
// send headers to keep connection alive
const headers = {
'Content-Type': 'text/event-stream',
'Connection': 'keep-alive',
'Cache-Control': 'no-cache'
};
res.writeHead(200, headers);
// send client a simple response
res.write('you are subscribed');
// store `res` of client to let us send events at will
client = res;
// listen for client 'close' requests
req.on('close', () => { client = null; }
});
// send refresh event (must start with 'data: ')
function sendRefresh() {
client.write('data: refresh');
}
Now the server can send a refresh event at any time by simply calling sendRefresh()
.现在服务器可以通过简单地调用sendRefresh()
随时发送刷新事件。
lite-server:精简服务器:
If you are running the server locally on your development computer, refreshing the browser is trivially easy.如果您在开发计算机上本地运行服务器,刷新浏览器非常简单。 lite-server is a module that will refresh the browser whenever it detects a change to source files. lite-server是一个模块,它会在检测到源文件发生更改时刷新浏览器。 It's very handy.它非常方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.