express 支持 history mode 模式

众所周知,当 vue 或 react 配置为 history 模式时,使用普通的 http 服务器刷新是会导致 404 的。这是因为刷新时是从服务器请求路由对应的页面,但服务器上其实是没有这个页面的。不刷新时跳转的那个路由是浏览器自己维护的一个 h5 功能。

那如何解决这个问题呢?通常需要在 ngrok 里配置,但本文要讲的是使用 express 的方式,代码也比较简单,已亲测可用。

参考

const express = require('express');
const path = require('path');
const history = require('connect-history-api-fallback');

const app = express();

const staticFileMiddleware = express.static(path.join(__dirname + '/dist'));

app.use(staticFileMiddleware);
app.use(
  history({
    disableDotRule: true,
    verbose: true,
  }),
);
app.use(staticFileMiddleware);

app.get('/', function(req, res) {
  res.render(path.join(__dirname + '/dist/index.html'));
});

var server = app.listen(process.env.PORT || 8080, function() {
  var port = server.address().port;
  console.log('App now running on port', port);
});

为了方便,后面会把这个功能集成的 mockm 里,以后想要这个功能,敲几个字符即可搞定。

原文地址:https://www.cnblogs.com/daysme/p/14590974.html