node.js使用Koa搭建基礎項目(入門級)


 Koa2 需要 v7.60 以上的 node.js 環境

一、創建項目

  1.手動創建一個項目目錄,然后快速生成一個 package.json 文件

    $ npm init -y

  安裝 koa    //當前版本 2.4.1

    $ npm install koa -s

  然后創建一個 app.js

const Koa = require('koa');
const app = new Koa();
 
app.use(async ctx => {
 ctx.body = 'hello 你好';
});
 
app.listen(3000);

  在cmd中輸入node app.js就可以啟動項目了,在瀏覽器輸入http://localhost:3000/ 查看效果

  

  或者你在package.json,更改代碼:

  

  輸入命令,npm start也是一樣的,可以運行項目,這樣一個最基礎的koa應用就好了!

   2.利用腳手架 koa-generato 來生成項目

    打開cmd,輸入:

     $ npm install koa-generator -g

     $ koa2 demo -e --ejs     后面是使用ejs模板的

   cd到demo文件下,輸入命令npm install

   運行項目 npm start

二、項目結構

  看一下利用腳手架生成的項目結構:

  

  先搞清楚bin里的www為項目入口,通過它引入app.js配置內容。

  node_moudel為模塊加載生成的文件夾,里面全是模塊功能的源碼。

  public公共文件夾,放一些樣式、頁面js邏輯、圖片。

  routers路由,功能為分發請求。

  views為視圖文件,jade是一個文本格式,其內容還可以是我們最熟悉的html。

  app.js和package.json是配置文件

三、配置路由

  手動創建項目時,需要配置路由。

const Koa = require('koa');
const app = new Koa();
 
app.use(async ctx => { //有一個 ctx,這是一個 Koa 提供的 Context 對象,封裝了 request 和 response
 ctx.body = 'hello 你好';
});
 
app.listen(3000);

  每一次 HTTP Request 都會創建一個 Context 對象,我們可以通過 Context.request.path 來獲取用戶請求的路徑,然后通過 Context.response.body 給用戶發送內容

  Koa 默認的返回類型是 text/plain,如果要返回一個 html 文件(或者一個模塊文件),就需要修改 Context.response.type

  另外,Context.response 可以簡寫,比如 Context.response.type 簡寫為 Context.type,Context.response.body 簡寫為 Context.type

  1.如果不用koa-router,這樣顯的很麻煩,下面來看一下:

    在目錄下創建views文件,在views新建index.html文件,在文件中寫入

   

 

  在app.js添加如下代碼:

const Koa = require('koa');
const fs = require('fs');
const app = new Koa();
 
app.use(async (ctx, next) => {
 if (ctx.request.path === '/') {
 ctx.type = 'text/html';
 ctx.body = fs.createReadStream('./views/index.html');
 } else {
 await next();
 }
});
 
app.listen(3000);

  運行項目,node app.js.  在瀏覽器輸入:http://localhost:3000,就可以顯示出index.html頁面了,如果網址輸入錯誤的話,頁面就會顯示 no found

   2.引入路由中間件koa-router

    安裝koa-router,   $ npm install koa-router

    2.1.在根目錄下創建一個routes目錄,存放路由文件,新建index.js文件   
// routes/index

const fs = require('fs');
const router = require('koa-router')() // 引入自調用
 
router.get('/', async (ctx, next) => {
 ctx.type = 'text/html';
 ctx.body = fs.createReadStream('./views/index.html');
});
 
module.exports = router

    修改app.js文件:

// app.js
 
const Koa = require('koa');
const app = new Koa();
 
const index = require('./routes/index')
app.use(index.routes(), index.allowedMethods())
 
app.listen(3000);

    運行項目,node app.js

四、靜態資源加載

  在實際項目中,需要加載很多靜態文件,如css、js文件,但是你沒有使用插件,靜態資源是無法顯示的,舉個例子:

  在根目錄下新建public文件,在public文件下新建css文件,css文件下新建index.css文件

   

index.css

h1{
    color: red;
}

  在index.html文件中引入index.css文件,再運行項目,是沒有效果的:

  

   使用koa-static -S加載靜態資源  $ npm install koa-static -S

  在app.js中新增如下代碼:  

const static = require('koa-static');
// 將 public 目錄設置為靜態資源目錄
const main = static(__dirname + '/public');
app.use(main);

  然后在index.html相對引入就可以了,運行就可以看到紅色的字體了。

<link rel="stylesheet" href="/css/index.css">

 五、模板引擎

  上面加載html文件是使用fs模塊的,下面使用koa-views中間件來加載html文件

  安裝koa-views $ npm install koa-views -S

  在app.js中將views目錄設置為模板目錄:

const views = require('koa-views')
app.use(views(__dirname + '/views')); // html文件、ejs文件、pug文件等......

在路由文件中,使用render方法:

const router = require('koa-router')()
 
router.get('/', async (ctx, next) => {
    await ctx.render('index');
});
 
module.exports = router

  運行項目就可以啦,記錄下每天學習內容...

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM