zoukankan      html  css  js  c++  java
  • 3、KOA模板引擎+访问静态资料中间件

    一、Koa模板引擎初识
    1、安装中间件 : npm i --save koa-views
    2、安装ejs模板引擎 :npm i --save ejs
    3、编写模板:<%= title %> 是调用传递的数据。可以自定义

    <!DOCTYPE html>
    <html>
    <head>
        <title><%= title %></title>http://jspang.com/wp-admin/post.php?post=2760&action=edit#
    </head>
    <body>
        <h1><%= title %></h1>
        <p>EJS Welcome to <%= title %></p>
    </body>
    </html>
    

    4、编写

    const Koa = require('koa');
    const app = new Koa();
    const path = require('path');
    const views = require('koa-views');
    
    //加载模板引擎
    //'./view' 是文件夹的路径,也就是模板所在的位置
    app.use(views(path.join(__dirname,'./view'),{
        extension:'ejs'
    }))
    
    //调用模板引擎
    app.use(async(ctx)=>{
        let title = "hello Koa2"
        //通过ctx.render调用的方法模板,index是模板的名称,title是传递的东西
        await ctx.render('index',{
            title
        })
    })
    
    app.listen(3000,()=>{
        console.log("OK,3000")
    })
    

    二、访问静态资料中间件
    1、在服务器环境中,我们不能直接通过浏览器地址来打开,或者获取一个文件夹里面的内容,如图片,那么就需要用到static的中间件了
    2、安装:npm i --save koa-static
    3、建一个文件夹名称为什么:static 并且放入 一些文件或者图片。 名称随便起
    4、使用和书写

    const Koa = require('koa');
    //引入地址变量和静态资源中间件
    const static = require('koa-static');
    const path = require('path');
    
    const app = new Koa();
    
    let staticPath = './static'
    
    //使用访问静态中间件,staticPath 是地址 文件夹  
    app.use(static(path.join(__dirname,staticPath)))
    
    app.use(async(ctx)=>{
        ctx.body = 'aaaaaaaaaa'
    })
    
    app.listen(3000,()=>{
        console.log("OK,3000")
    })
    

      

  • 相关阅读:
    CF1202F You Are Given Some Letters...
    CF1178E Archaeology
    PTA (Advanced Level) 1005 Spell It Right
    PTA (Advanced Level) 1004 Counting Leaves
    Qt5——从零开始的Hello World教程(Qt Creator)
    PTA (Advanced Level) 1003 Emergency
    PTA (Advanced Level) 1002 A+B for Polynomials
    HDU 1272 小希的迷宫
    FZU 2150 Fire Game
    HihoCoder
  • 原文地址:https://www.cnblogs.com/chengxiang123/p/9520698.html
Copyright © 2011-2022 走看看