关于node.js:koa2用中间件koastaticrouter-搭建静态资源服务器实现多级路由加载静态资源

源码及应用阐明 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

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

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')
})

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理