按上图所示,以public下的ww文件夹为例,故访问路径为http://www.abc.com/ww/
normal.js
注意顺序,如果/*优先注册,会导致ww这种二级目录失效,所以/*应该放最后
const Router = require("koa-router")
const router = new Router()
const fs = require("fs")
const path = require("path")
//注意顺序,如果/*优先注册,会导致ww这种二级目录失效,所以/*应该放最后
router.get("/ww/*", (ctx, next) => {
let filePath = path.join(__dirname, "../public/ww/index.html") //图片地址
ctx.set("Content-Type", "text/html;charset=utf-8")
ctx.body = fs.readFileSync(filePath)
})
router.get("/*", (ctx, next) => {
//ctx.body = "这是首页"
let filePath = path.join(__dirname, "../public/index.html") //图片地址
ctx.set("Content-Type", "text/html;charset=utf-8")
ctx.body = fs.readFileSync(filePath)
})
module.exports = router
index.js–将该目录下的js文件自动载入并注册路由(即backend.js,frontend.js,normal,js里的路由进行注册)
const compose = require('koa-compose')
const glob = require('glob')
const { resolve } = require('path')
registerRouter = () => {
let routers = [];
glob.sync(resolve(__dirname, './', '**/*.js'))
.filter(value => (value.indexOf('index.js') === -1))
.map(router => {
routers.push(require(router).routes())
routers.push(require(router).allowedMethods())
})
return compose(routers)
}
module.exports = registerRouter
注意,中间件staticFiles要在router前注册,它会影响到目录里的其他文件是否可以被直接访问
app.js
const Koa = require("koa2")
const app = new Koa()
const staticFiles = require("koa-static")
//先注册staticFiles中间件,后注册路由中间件
app.use(staticFiles(__dirname + "/public/"))
const registerRouter = require("./routes")
app.use(registerRouter())
在vue-router中,需要把默认的/替换为/ww
const router = createRouter({
history: createWebHistory("/ww"),
routes,
})
版权声明:本文为aexwx原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。