国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > JS > 正文

使用koa2創(chuàng)建web項目的方法步驟

2024-05-06 16:48:59
字體:
供稿:網(wǎng)友

Github上有一個express風(fēng)格的koa腳手架,用著挺方便,一直以來使用koa開發(fā)web項目用的也都是那個腳手架,今天想自己從頭搭一個web項目,就折騰了一下

腳手架地址: https://github.com/17koa/koa-generator

初始化

使用 npm init 初始化一個nodejs項目

mkdir koa-democd koa-demonpm 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');// 初始化koaconst 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')();// routeconst 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

在根目錄運行命令啟動項目

nodemon app.js

測試

訪問 http://localhost:3000/view/

koa2,創(chuàng)建,web項目

訪問 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í)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。


注:相關(guān)教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 东辽县| 玉田县| 古交市| 邵东县| 邯郸县| 峨眉山市| 太谷县| 黔东| 辉县市| 美姑县| 河西区| 纳雍县| 沁水县| 沅江市| 那曲县| 永靖县| 安西县| 昌都县| 平南县| 青州市| 霍山县| 庐江县| 齐河县| 建湖县| 康保县| 汉源县| 平湖市| 印江| 公主岭市| 临夏县| 稷山县| 伊春市| 应城市| 治多县| 翼城县| 罗城| 洱源县| 潼南县| 海阳市| 乌拉特中旗| 宁武县|