之前说过,当服务器遇到 src、href 等链接外部资源的标签时,会把 引用路径当作 res.url 路径去请求,那么在 koa 中遇到这种情况,需要借助于 中间件 koa-static
(1) 安装 koa-static
npm i koa-static --save
(2) 使用
代码:
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const bodyparser = require('koa-bodyparser')
const Router = require('koa-router')
const path = require('path')
const router = new Router()
const serve = require('koa-static')
app.use(bodyparser())
// 静态资源跟路径 serve(path)
app.use(serve(path.join(__dirname, 'public')))
app.use(views(path.join(__dirname, 'views'), {
extension: 'ejs'
}))
router.get('/', async (ctx) => {
await ctx.render('index')
})
app.use(router.routes())
app.listen(3000)
index.ejs:
路径是相对于静态资源根路径的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>index</title>
<link rel="stylesheet" href="/index.css">
</head>
<body>
<div class="content">11</div>
<img src="/actor.jpg" alt="">
<script src='/index.js'></script>
</body>
</html>
单独访问静态资源:
http://local.djtest.cn:3000/index.css
http://local.djtest.cn:3000/actor.jpg
http://local.djtest.cn:3000/index.js
原理:当访问的时候,先去设置的静态资源根目录下找,找到读取文件内容,找不到再next()