关于前端:koa2用中间件-koastaticrouter-快速搭建静态资源服务器实现多级路由加载静态资源

1次阅读

共计 887 个字符,预计需要花费 3 分钟才能阅读完成。

源码及应用阐明 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')
})
正文完
 0