使用 express 极简处理前端路由的 history 模式问题

主要使用的中间件:
bripkens/connect-history-api-fallback: Fallback to index.html for applications that are using the HTML 5 history API

serve.js

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

const app = express();

// 先定义后端路由
app.get("/health", function (req, res) {
  res.send("ok");
});

// 再使用 history 中间件
app.use(history());

// 最后配置 静态资源文件
app.use(express.static(__dirname + "/public"));

// 监听端口号
app.listen(8081, () => {
  console.log("服务已启动");
});

执行:node serve.js

PS 需要前端处理路由不匹配问题(404)

在 koa 中使用这个中间件

上面这个中间件是基于 express 的,在 koa/egg.js 中使用,可以借助 koa-connect 这个库。

详见:每天一个npm包:koa-connect - 知乎
GitHub - vkurchatkin/koa-connect: Use connect and express middleware in koa

参考:
教你怎么快速搭建一个 Node + Express 静态服务器 - 简书
Express 路由
HTML5 History 模式 | Vue Router

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/jasongrass/p/15703534.html