1、安装
cnpm install koa-static --save
2、引入
const static=require('koa-static');
3、配置中间件
可配置多个静态资源
app.use(static('static')); 即外部文件可直接写static下的路径引入
4、使用
引入static下的路径,而非绝对路径
代码示例:
server.js:
const Koa=require('koa');
const Router=require('koa-router');
const views=require('koa-views');
const commonm=require('./public/common');
const bodyParser=require('koa-bodyparser');
const static=require('koa-static');
const app=new Koa();
const router=new Router();
//配置模板引擎
// app.use(views('views',{extension:"ejs" })); //文件后缀必须为.ejs
app.use(views('views',{map:{html:'ejs'}}));
//配置static
app.use(static('static'));
app.use(router.routes())
.use(router.allowedMethods());
//公共数据
app.use(async(ctx,next)=>{
ctx.state={
username:'jeff2'
};
await next();
})
app.use(bodyParser());
router.get('/',async(ctx,next)=>{
await ctx.render("index",{
title:'jeff',
info:"<h2 style='color:red'>渲染</h2>"
});
})
router.get('/news',async(ctx,next)=>{
await ctx.render('news',{
arr:[1,2,3,4]
})
})
//路由中间件
router.get('/det',async(ctx,next)=>{
// ctx.body='det1';
console.log('aaa');
await next();
})
router.get('/det',async(ctx,next)=>{
ctx.body='det2';
})
router.post('/info',async (ctx,next)=>{
// var data=await commonm.Posts(ctx);
var data=ctx.request.body.name;
ctx.body=data;
})
router.get('/msg',async(ctx,next)=>{
ctx.body=ctx.query.id;
})
//动态路由
router.get('/home/:aid/:aic',async(ctx,next)=>{
ctx.body=ctx.params.aid+ctx.params.aic;
})
app.listen(3000,()=>{
console.log('this koa server is running at http://localhost:3000/');
})
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="css/index.css">
</head>
<body>
<div>
ejs模板
<h2 class='tit'><%=title%></h2>
<%- include('../public/test.html'); %>
<h3 class='tit'>jefff</h3>
<%-info%>
<img src="img/1.jpg" alt="">
</div>
</body>
</html>