koa

koa实现静态资源部署

koa部署静态资源以及避免刷新404

Posted by Xshellv on 2021-09-14

本文主要介绍了使用 Koa 进行静态资源部署,解决刷新404的问题。并且在设计service api路由的情况下,保证与静态资源互不影响。

koa-static介绍

koa-static 就是koa中最常用的、较为成熟的静态web托管服务中间件 ,在koa中常用于比如html、css、js等资源:

1
2
3
4
5
// 使用
const koaStatic = require("koa-static");

app.use(koaStatic(path.resolve(__dirname, "images")));
app.use(koaStatic(path.resolve(__dirname, "bundle")));

由于我的bundle的入口文件为 index.html,因此设置如上后,我们能在在根路径下打开页面。但是如果我们点击前端路由后再次刷新会得到一个404的页面,道理其实也很简单,就是该路由被Koa拦截后当作controller的路径进行匹配结果没有找到因此返回404。下面我们继续改造:

koa-views使用

koa-views 是一个视图管理模块,它的灵活度很高,支持很多的模版引擎。具体可看github介绍。

1
2
3
const views = require("koa-views");
// 注册模板文件,指定相应文件夹
app.use(views(path.resolve(__dirname, "bundle")));

有个上面的koa-views我们就可以在 ctx 上获得一个 render 方法。

静态资源请求和service api分离

现在我们使用 ctx.render() 写上一个静态资源匹配规则的中间件,让path以 /ps 开头的走 index.html 渲染,否则移交下一个中间件处理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
app.use(async (ctx, next) => {
if (ctx.request.path.startsWith("/ps")) {
await ctx.render("index");
}
await next();
});

router.post("/upload", (ctx, next) => {
// ...
});

router.get("/public/images/:imgName", (ctx, next) => {
// ....
});

app.use(router.routes());
app.use(router.allowedMethods());

app.listen(process.env.PORT, () => {
console.log(`server run: http://127.0.0.1:${process.env.PORT}`);
});

至此我们就能完成整个静态资源的部署,同时又不影响service的路由设计!