使用koa2創(chuàng)建web項(xiàng)目的方法步驟
Github上有一個express風(fēng)格的koa腳手架,用著挺方便,一直以來使用koa開發(fā)web項(xiàng)目用的也都是那個腳手架,今天想自己從頭搭一個web項(xiàng)目,就折騰了一下
腳手架地址: https://github.com/17koa/koa-generator
初始化
使用 npm init 初始化一個nodejs項(xiàng)目
mkdir koa-demo cd koa-demo npm init
一直回車即可,創(chuàng)建好之后目錄里會有一個 package.json 文件
安裝依賴
npm install --save koa koa-body koa-logger koa-json-error koa-router koa-static koa-njk
- koa
- koa-body 解析http請求參數(shù)的,支持 multipart/form-data application/x-www-urlencoded application/json 三種參數(shù)類型
- koa-logger 顯示http請求的日志
- koa-router 路由
- koa-json-error 程序出異常輸出json
- koa-static 映射靜態(tài)資源文件
- koa-njk nunjucks模板解析
配置
在根目錄下創(chuàng)建 app.js 然后貼上下面代碼,代碼內(nèi)有注釋,很簡單
// 引入依賴
const koa = require('koa');
const koa_body = require('koa-body');
const koa_json_error = require('koa-json-error');
const koa_logger = require('koa-logger');
const koa_static = require('koa-static');
const koa_njk = require('koa-njk');
const path = require('path');
// 初始化koa
const app = new koa()
// 引入路由配置文件,這個在下面說明
const routers = require('./routes/routers');
// 配置程序異常輸出的json格式
app.use(koa_json_error((err) => {
return {
code: err.status || 500,
description: err.message
}
}));
// 添加靜態(tài)資源文件映射
app.use(koa_static(path.join(__dirname, 'static')))
// 添加nunjucks模板
app.use(koa_njk(path.join(__dirname, 'views'), '.njk', {
autoescape: true,
}, env => {
// 添加自己的過濾器
env.addFilter('split', (str, comma) => {
if (str) {
return str.split(comma);
} else {
return '';
}
});
}));
// 解析表單提交參數(shù)
app.use(koa_body());
// 顯示請求和響應(yīng)日志
app.use(koa_logger());
// 路由
app.use(routers.routes())
// 程序啟動監(jiān)聽的端口
const port = 3000;
app.listen(port);
console.log('Listening on ' + port);
路由
在根目錄下創(chuàng)建 routes 文件夾
在 routes 文件夾內(nèi)創(chuàng)建 index.js routers.js 文件
在 index.js 文件內(nèi)添加如下代碼
// 測試路由,輸出請求的參數(shù)
exports.index = async ctx => {
const body = ctx.request.body;
const query = ctx.request.query;
const params = ctx.params;
ctx.body = {
body: body,
query: query,
params: params,
};
}
// 測試nunjucks模板
exports.view = async ctx => {
await ctx.render('index', {
title: 'Koa'
})
}
// 測試異常
exports.test_error = async ctx => {
throw new Error('測試異常');
}
配置路由,在 routers.js 文件內(nèi)配置路由
const router = require('koa-router')();
// route
const index = require('./index');
router.get('/view', index.view);
router.get('/index', index.index);
router.get('/index:id', index.index);
router.post('/index', index.index);
router.get('/test_error', index.test_error);
module.exports = router
靜態(tài)文件
在根目錄創(chuàng)建文件夾 static 添加 app.css 文件,寫上下面代碼
body {
background-color: #eee;
}
模板
在根目錄創(chuàng)建文件夾 views 添加 index.njk 文件,寫上下面代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title></title> <link rel="stylesheet" href="/app.css" rel="external nofollow" > </head> <body> Hello, ! <br> <ul> <!-- 使用自定義的過濾器 --> </ul> </body> </html>
啟動
安裝 nodemon
npm install -g nodemon
在根目錄運(yùn)行命令啟動項(xiàng)目
nodemon app.js
測試
訪問 http://localhost:3000/view/

訪問 http://localhost:3000/index/ 可以看到輸出的json
{
"body": {},
"query": {},
"params": {}
}
訪問 http://localhost:3000/index/?id=1
{
"body": {},
"query": {
"id": "1"
},
"params": {}
}
訪問 http://localhost:3000/index/1
{
"body": {},
"query": {},
"params": {
"id": "1"
}
}
POST 請求 curl -X POST http://localhost:3000/index/ -d '{"id": "1"}' -H 'Content-Type:application/json'
{
"body":{
"id":"1"
},
"query":{},
"params":{}
}
訪問 http://localhost:3000/test_error
{
"code": 500,
"description": "測試異常"
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Node.js刷新session過期時間的實(shí)現(xiàn)方法推薦
下面小編就為大家?guī)硪黄狽ode.js刷新session過期時間的實(shí)現(xiàn)方法推薦。小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-05-05
Node.js使用bcrypt-pbkdf實(shí)現(xiàn)密碼加密
在這個數(shù)字時代,保護(hù)用戶密碼的重要性不言而喻,作為一名資深的前端開發(fā)工程師和技術(shù)博客作者,今天我將帶你詳細(xì)了解如何在 Node.js 環(huán)境中利用 bcrypt-pbkdf 模塊進(jìn)行密碼的哈希處理,確保你的應(yīng)用安全性得到有效提升,需要的朋友可以參考下2024-05-05

