当前位置:网站首页>Koa2 fast build server
Koa2 fast build server
2022-07-21 20:48:00 【Fan Xiaoduo】
Get started
- New folder initialization project , Command line input
npm init -y
- install koa, Input
npm i koa
- Create a new
app.js
file - app Content
// 1. establish KOA Instance object of const Koa = require('koa') const app = new Koa() // 2. Binding middleware ( Write response functions ) // ctx: Context ,web Containers ,ctx.request ctx.response // next: Next middleware , Whether the next layer middleware can be implemented , Depending on next Is this function called app.use(async (ctx,next) => { // What I just did in middleware ctx.response.body = 'Hello world!' await next() // next() Back to a promise object // What to do after all the middleware in the inner layer }) ... // 3. Monitor port number app.listen(8888)
project
Get ready
- Initialize project
- install koa
- establish
middleware
Folder : Storage middleware (koa_response_data.js
、koa_response_duration.js
、koa_response_header.js
) - establish
data
Folder : For storage data data , Simulate getting data from a database - establish
utils
Folder : Depositfile_utils.js
, obtain data File data method - To write
app.js
file// The server's entry file // 1. establish KOA Instance object of const Koa = require('koa') const app = new Koa() // 2. Binding middleware // The total time is const respDurationMiddleware = require('./middleware/koa_response_duration') app.use(respDurationMiddleware) // Response header middleware const respHeaderMiddleware = require('./middleware/koa_response_header') app.use(respHeaderMiddleware) // Logic processing middleware const respDataMiddleware = require('./middleware/koa_response_data') app.use(respDataMiddleware) // 3. Binding port number 8888 app.listen(8888)
- To write
koa_response_duration.js
file ( The total time is )// Middleware for computing server consumption module.exports = async (ctx, next) => { // Record the start time const start = Date.now() // Let the inner middleware be implemented await next() // Record the end time const end = Date.now() // Set the response header X-Response-Time const duration = end - start // ctx.set Set the response header ctx.set('X-Response-Time', duration + 'ms') }
- To write
koa_response_header.js
file ( Response header middleware )// Middleware for setting response headers module.exports = async (ctx, next) => { const contentType = 'application/json; charset=utf-8' ctx.set('Content-Type', contentType) ctx.set("Access-Control-Allow-Origin", "*") ctx.set("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE") await next() }
- To write
koa_response_data.js
file ( Logic processing middleware )// Middleware for business logic , Read something json File data const path = require('path') const fileUtils = require('../utils/file_utils') module.exports = async (ctx, next) => { // according to url const url = ctx.request.url // /api/seller ../data/seller.json let filePath = url.replace('/api', '') // /seller filePath = '../data' + filePath + '.json' // ../data/seller.json filePath = path.join(__dirname, filePath) try { const ret = await fileUtils.getFileJsonData(filePath) ctx.response.body = ret } catch (error) { const errorMsg = { message: ' Failed to read file contents , File resource does not exist ', status: 404 } ctx.response.body = JSON.stringify(errorMsg) } console.log(filePath) await next() }
- To write
file_utils.js
file// Tools and methods for reading files const fs = require('fs') module.exports.getFileJsonData = (filePath) => { // According to the path of the file , Read the contents of the file return new Promise((resolve, reject) => { fs.readFile(filePath, 'utf-8', (error, data) => { if(error) { // Failed to read file reject(error) } else { // Read file successful resolve(data) } }) }) }
边栏推荐
- thinkphp5.1 利用 PHPMailer 发送邮件
- 24. [judge whether it is an integer with bytes]
- Comsol热传导方法求解迷宫问题(路径规划)
- OpenFOAM中的多孔介质
- Swift navigation bar color device and remove the lower edge line
- uniapp自定义导航栏按钮及按钮点击事件
- uniapp 下拉刷新、上拉加载更多、最常见的节流场景
- Output statements on the console
- Solve the problem that Safari browser blocks window open
- Click the back button to return to the previous page
猜你喜欢
JS operation mechanism
VOF phase transition equation in openfoam
Nodejs读取并解析xml的DOM
宽字节注入学习记录
TP5对接免签FM支付接口
ecshop漏洞复现
MySQL import and export & View & Index & execution plan
Realization of interface displacement by linear Schrodinger equation
Flutter报错总结:There are multiple heroes that share the same tag within a subtree.
JS数据类型在内存上的储存原理
随机推荐
12. [i/o flow get() and getline() and put() functions]
Flutter报错总结:There are multiple heroes that share the same tag within a subtree.
BUUCTF-web-随便注
JS uses recursion to implement deep copy of objects
thinkphp5.1 利用 PHPMailer 发送邮件
推荐一个好用的 所见即所得的 markdown 编辑器 Mark Text
Hot update in development mode to speed up the code update of development environment
Realization of interface displacement by linear Schrodinger equation
Boundary layer integral equation and Marangoni effect
宽字节注入学习记录
php截取得到指定字符串之前与之前后的内容
window. history. back(); The problem that layer cannot be closed after returning
npm相关资料
flutter 报错记录:navigator.dart‘: Failed assertion: line 4041 pos 12: ‘!_debugLocked‘: is not true.
JS使用递归实现对象的深拷贝
Nodejs+Express使用 cors 中间件解决跨域问题
thinkphp6使用EasyWeChat5.x之公众号开发(一)
OpenFoam中的VOF相变方程
Redis与memcached有何不同
thinkphp设置单位时间内限制 ip 的请求