koa中间件 koa-static-router中间件搭建静态资源服务器, 实现多个&&多层路由加载静态资源
安装
$ npm install koa-static-router
Usage
简单配置
app.use(static('public')) //默认配置: {dir:public route:'/public'}
单个路由
const static = require('koa-static-router');
app.use(static({
dir, //静态资源目录对于相对入口文件index.js的路径
router //路由命名
}))
多个路由
选择多个路由时,请确保路由长度相同
'/static/' - >路由长度 = 1
'/static/image1/' - >路由长度 =2
const static = require('koa-static-router');
app.use(static([
{
dir', //静态资源目录对于相对入口文件index.js的路径
router //路由命名
},{
dir,
router
}
]))
git clone
cd koa-static-router
npm install
npm start
访问 localhost:3000/public/image/dir/1.png
image
访问 localhost:3000/static/image/dir/2.png
image
const Koa = require('koa')
const app = new Koa()
const static = require('koa-static-router');
// 单个路由
// app.use(static({
// dir:'public',
// router:'/static/' //路由长度 =1
// }))
//多个路由
app.use(static([
{
dir:'public', //静态资源目录对于相对入口文件index.js的路径
router:'/public/image/' //路由命名 路由长度 =2
},{
dir:'static', //静态资源目录对于相对入口文件index.js的路径
router:'/static/image/' //路由命名 路由长度 =2
}
]))
app.use( async ( ctx ) => {
ctx.body = 'hello world'
})
app.listen(3000, () => {
console.log('build success')
})