当前位置: 首页 > 后端技术 > Node.js

[koa2]使用中间件koa-static-router搭建静态资源服务器,实现多级路由加载静态资源

时间:2023-04-03 10:13:24 Node.js

源码及使用说明Git仓库安装npminstallkoa-static-router用法singlerouteconststatic=require('koa-static-router');app.use(static({dir,//相对入口文件的静态资源目录index.js路径route//路由命名}))多条路由选择多条路由时,请保证路由长度相同'/static/'->routelength=1'/static/image1/'->routelength=2conststatic=require('koa-static-router');app.use(static([{dir,//static的路径resource目录到相对入口文件index.jsrouter//Routenaming},{dir,router}]))Demogitclonecdkoa-static-routernpminstallnpmstartaccesslocalhost:3000/public/image/dir/1.pngaccesslocalhost:3000/static/image/dir/2.pngconstKoa=require('koa')constapp=newKoa()conststatic=require('koa-static-router');//单路由//app.use(static({//dir:'public',//router:'/static/'//Routelength=1//}))//多条路由app.use(static([{dir:'public',//静态资源目录到相对入口文件的路径index.jsrouter:'/public/image/'//路由命名routelength=2},{dir:'static',//该路径静态资源目录到相对入口文件index.jsrouter:'/static/image/'//路由命名routelength=2}]))app.use(async(ctx)=>{ctx.body='helloworld'})app.listen(3000,()=>{console.log('构建成功')})