如何使用 node.js 从服务器端刷新浏览器? [英] How do I refresh browser from server-side with node.js?

查看:112
本文介绍了如何使用 node.js 从服务器端刷新浏览器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 html-webpack-plugin 和 webpack-dev-middleware (webpack-hot-middleware) 互操作中的 HMR 错误,我想在更改 html 文件时(在开发过程中)重新加载页面.

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.

这里有两个我遇到这个问题的存储库,两者都有问题.

Here are two repositories where I got this problem, there are issues in both.

如何使用此工具重新加载页面?

  • Node.js
  • 快递
  • webpack-dev-middleware

推荐答案

有几种方法可以从服务器刷新客户端的浏览器.

There are a few ways to refresh a client's browser from the server.

服务器发送的事件:

一种适用于浏览器和服务器的简单方法是使用服务器发送事件.最小的过程是:

One simple method that works across browsers and servers uses server-sent events. The minimal process is:

  1. 客户端使用 EventSource():

var evtSource = new EventSource("<server_URL>/subscribe");

  1. 客户端为传入消息设置侦听器:

evtSource.onmessage = function () { myPageRefresh() };

在服务器端,为 GET/subscribe 请求设置处理程序并跟踪订阅的客户端:

On the server side, set up a handler for GET /subscribe requests and keep track of the subscribed client:

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');
}

现在服务器可以通过简单地调用 sendRefresh() 随时发送刷新事件.

Now the server can send a refresh event at any time by simply calling 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. It's very handy.

这篇关于如何使用 node.js 从服务器端刷新浏览器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆