三、KOA模板引擎+訪問靜態資料中間件

1、Koa模板引擎初識
一、安裝中間件 : npm i --save koa-views
二、安裝ejs模板引擎 :npm i --save ejs
三、編寫模板:<%= title %> 是調用傳遞的數據。能夠自定義javascript

<!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>

四、編寫php

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")
})

 

2、訪問靜態資料中間件
一、在服務器環境中,咱們不能直接經過瀏覽器地址來打開,或者獲取一個文件夾裏面的內容,如圖片,那麼就須要用到static的中間件了
二、安裝:npm i --save koa-static
三、建一個文件夾名稱爲何:static 而且放入 一些文件或者圖片。 名稱隨便起
四、使用和書寫html

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")
})
相關文章
相關標籤/搜索