likes
comments
collection
share

【koa2】用中间件 koa-static-router 快速搭建静态资源服务器,实现多级路由加载静态资源

作者站长头像
站长
· 阅读数 28

源码及使用说明 Git仓库

安装

npm install koa-static-router

Usage

  • 单个路由
const static = require('koa-static-router');
 app.use(
   static({
     dir,  //静态资源目录对于相对入口文件index.js的路径
     route   //路由命名
   })
 )
  • 多个路由

选择多个路由时,请确保路由长度相同 '/static/' - >路由长度 = 1 '/static/image1/' - >路由长度 =2

const static = require('koa-static-router');

app.use(
  static([
    {
      dir,     //静态资源目录对于相对入口文件index.js的路径
      router    //路由命名
    },{
      dir,
      router  
    }
  ])
)

Demo

git clone
cd koa-static-router
npm install 
npm start
  1. 访问 localhost:3000/public/image/dir/1.png

【koa2】用中间件 koa-static-router 快速搭建静态资源服务器,实现多级路由加载静态资源

  1. 访问 localhost:3000/static/image/dir/2.png

【koa2】用中间件 koa-static-router 快速搭建静态资源服务器,实现多级路由加载静态资源

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')
})
转载自:https://segmentfault.com/a/1190000039176140
评论
请登录