运行打包文件
当打包了 vue 项目之后,可以启动本地静态资源服务器,运行 /dist 下的资源
const Koa = require('koa');
const app = new Koa();
const static = require('koa-static');
const Router = require('koa-router');
const path = require('path');
const mount = require('koa-mount'); // 支持请求前缀
const router = new Router();
const fs = require('fs');
app.use(mount('/fzbc/h5', static(path.join(__dirname, './dist/'))));
router.get('/', ctx => {
ctx.redirect('/fzbc/h5');
});
// 回退路由:解决 vue 设置了 history 路由会出现刷新页面 404 的问题
app.use(async (ctx, next) => {
await next();
if (ctx.status === 404 && ctx.path.includes('.')) {
ctx.throw(404, 'The requested resource was not found.');
} else if (ctx.status === 404) {
ctx.type = 'html';
ctx.body = fs.createReadStream(path.resolve('./dist/index.html'));
}
});
// 挂载路由
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3300, () => { console.log('http://localhost:3300') });
静态资源服务器
简单实现一个 静态资源服务器
示例代码
-
index.js
const Koa = require("koa"); const koaStatic = require("./koa-static"); const path = require("path"); const app = new Koa(); app.use(require("./koa-fallback")); app.use(koaStatic(path.resolve(__dirname, "public"))); app.listen(9527, () => { console.log("server listening"); });
-
koa-static.js
const fs = require("fs"); const path = require("path"); const mime = require("mime"); // 用于获取文件路径 async function getFileName(urlPath, root) { const subPath = urlPath.substr(1); const filename = path.resolve(root, subPath); try { const stat = await fs.promises.stat(filename); if (stat.isDirectory()) { // 是目录 const newUrlPath = path.join(urlPath, "index.html"); return await getFileName(newUrlPath, root); } else { return filename; } } catch { // 文件不存在 return null; } } module.exports = function (root) { return async function (ctx, next) { if (ctx.method !== "GET") { await next(); return; } const filename = await getFileName(ctx.path, root); if (!filename) { // 文件不存在 await next(); // 一定要写上 await,如果不写上 await 代表=>需要中间件但是,不等待中间件的执行结构 return; } // 得到文件内容 ctx.body = fs.createReadStream(filename); ctx.type = mime.getType(filename); // 设置类型,下载文件、渲染文件、...... }; };
-
koa-fallback.js
module.exports = async function (ctx, next) { // ctx.path: /a => ctx.path: /index.html if ( ctx.method === "GET" && ctx.headers.accept.includes("text/html") && !ctx.path.includes(".") ) { ctx.path = "/index.html"; } await next(); };
附件下载
Koa👉 常用中间件
上一篇