koa static静态资源

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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值