kaotongxinmokuai v1.0.3
Expressive HTTP middleware framework for node.js to make web applications and APIs more enjoyable to write. Koa's middleware stack flows in a stack-like manner, allowing you to perform actions downstream then filter and manipulate the response upstream.
Only methods that are common to nearly all HTTP servers are integrated directly into Koa's small ~570 SLOC codebase. This includes things like content negotiation, normalization of node inconsistencies, redirection, and a few others.
Koa is not bundled with any middleware.
Installation
Koa requires node v7.6.0 or higher for ES2015 and async function support.
$ npm install koa
Hello Koa
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server, {
connectionStateRecovery: {
// the backup duration of the sessions and the packets
maxDisconnectionDuration: 2 * 60 * 1000,
// whether to skip middlewares upon successful recovery
skipMiddlewares: true,
}
});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.get('/log.html', (req, res) => {
res.sendFile(__dirname + '/log.html');
});
// app.get('/index.html', (req, res) => {
// res.sendFile(__dirname + '/index.html');
// });
io.on('connection', (socket) => {
if (socket.recovered) {
console.log('心跳检测 重连成功');
// recovery was successful: socket.id, socket.rooms and socket.data were restored
} else {
console.log('心跳检测 重连失败');
// new or unrecoverable session
}
socket.on('send msg', (msg) => {
io.emit('send msg', msg);
});
});
server.listen(3000);
app.js
Getting started
- Kick-Off-Koa - An intro to Koa via a set of self-guided workshops.
- Workshop - A workshop to learn the basics of Koa, Express' spiritual successor.
- Introduction Screencast - An introduction to installing and getting started with Koa
Middleware
Koa is a middleware framework that can take two different kinds of functions as middleware:
- async function
- common function
Here is an example of logger middleware with each of the different functions:
async functions (node v7.6+)
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
body {
margin: 0;
padding-bottom: 3rem;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
#form {
background: rgba(0, 0, 0, 0.15);
padding: 0.25rem;
position: fixed;
bottom: 0;
left: 0;
right: 0;
display: flex;
height: 3rem;
box-sizing: border-box;
backdrop-filter: blur(10px);
}
#input {
border: none;
padding: 0 1rem;
flex-grow: 1;
border-radius: 2rem;
margin: 0.25rem;
}
#input:focus {
outline: none;
}
#form>button {
background: #333;
border: none;
padding: 0 1rem;
margin: 0.25rem;
border-radius: 3px;
outline: none;
color: #fff;
}
#messages {
list-style-type: none;
margin: 0;
padding: 0;
}
#messages>li {
padding: 0.5rem 1rem;
}
#messages>li:nth-child(odd) {
background: #efefef;
}
</style>
</head>
<body>
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off" /><button id="btn">Send</button>
</form>
</body>
<script src="/socket.io/socket.io.js"></script>
<script>
btn.onclick = function () {
if (!localStorage.getItem('token')) {
alert('weidenglu')
location.href = 'log.html'
}
}
const socket = io({
reconnectionDelay: 3000, // defaults to 1000
reconnectionDelayMax: 3000 // defaults to 5000
});
socket.on("connect", () => {
console.log("recovered?", socket.recovered);
setTimeout(() => {
if (socket.io.engine) {
// close the low-level connection and trigger a reconnection
socket.io.engine.close();
}
}, 3000);
});
socket.on("connect", () => {
if (socket.recovered) {
console.log('xintiaojiance chengong');
// any missed packets will be received
} else {
console.log('xintiaojiance shibai');
// new or unrecoverable session
}
});
var messages = document.getElementById('messages');
var form = document.getElementById('form');
var input = document.getElementById('input');
form.addEventListener('submit', function (e) {
e.preventDefault();
if (input.value && input.value.length < 200) {
socket.emit('send msg', input.value);
input.value = '';
}
});
socket.on('send msg', function (msg) {
var item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
</script>
</html>
index.html
Common function
// Middleware normally takes two parameters (ctx, next), ctx is the context for one request,
// next is a function that is invoked to execute the downstream middleware. It returns a Promise with a then function for running code after completion.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>denglu yemian</h1>
<input type="text" placeholder="yonghuming">
<input type="password" placeholder="mima">
<button id="btn">denglu</button>
</body>
<script src="/socket.io/socket.io.js"></script>
<script>
btn.onclick = function () {
localStorage.setItem('token', 'adawdzxefsdaafgvbajsbfuiewyfiybadf')
location.href = 'http://localhost:3000'
}
</script>
</html>
log.html
Koa v1.x Middleware Signature
The middleware signature changed between v1.x and v2.x. The older signature is deprecated.
Old signature middleware support will be removed in v3
Please see the Migration Guide for more information on upgrading from v1.x and using v1.x middleware with v2.x.
Context, Request and Response
Each middleware receives a Koa Context
object that encapsulates an incoming
http message and the corresponding response to that message. ctx
is often used
as the parameter name for the context object.
Koa provides a Request
object as the request
property of the Context
.
Koa's Request
object provides helpful methods for working with
http requests which delegate to an IncomingMessage
from the node http
module.
Here is an example of checking that a requesting client supports xml.
const query = require("../db/query");
const moment = require("moment");
const AddOrder = async (params) => {
let sql = `select a.*,a.count*b.price zprice from cart a join shop b on a.shopid = b.id where a.id in (${params.ids})`;
let cartdata = await query(sql);
let addsql = `insert into orders (ordercode,shopid,count,zprice,status,userid,createtime) values `;
for (let i = 0; i < cartdata.length; i++) {
let ordercode = Math.random().toFixed(10).slice(-10);
let shopid = cartdata[i].shopid;
let count = cartdata[i].count;
let zprice = cartdata[i].zprice;
let createtime = moment().format("YYYY-MM-DD HH:mm:ss");
addsql += `('${ordercode}',${shopid},${count},${zprice},0,${params.userid},'${createtime}'),`;
}
addsql = addsql.substring(0, addsql.length - 1);
let res = await query(addsql);
if (res.affectedRows > 0) {
let delsql = `delete from cart where id in (${params.ids})`;
let delres = await query(delsql);
if (delres.affectedRows > 0) {
return true;
}
}
return false;
};
const CheckOrders = async (params) => {
let sql = `select a.*,b.name,b.price from orders a join shop b on a.shopid = b.id where a.userid = ${params.userid}`;
if (params.name) {
sql += `and b.name like '%${params.name}%'`;
}
if (params.status != -1 && params.status != undefined) {
sql += `and a.status = ${params.status}`;
}
return await query(sql);
};
const UpdateOrderStatus = async (params) => {
let newstatus = -1;
if (params.status == 0) {
newstatus = 1;
} else if (params.status == 1) {
newstatus = 2;
} else if (params.status == 2) {
newstatus = 3;
} else if (params.status == 3) {
newstatus = 4;
} else if (params.status == 4) {
newstatus = 5;
} else if (params.status == 5) {
newstatus = 6;
}
let sql = `update orders set status = ${newstatus} where id = ${params.id}`;
return await query(sql);
};
const DeleteOrder = async (params) => {
let sql = `delete from orders where id = ${params.id} and status = 6`;
return await query(sql);
};
const Orderagain = async (params) => {
let sql = `select * from orders where id = ${params.id}`;
let orderdata = await query(sql);
if (orderdata[0].status != 6) {
return false;
}
let ordercode = Math.random().toFixed(10).slice(-10);
let createtime = moment().format("YYYY-MM-DD HH:mm:ss");
let sqlagain = `insert into orders (ordercode,shopid,count,zprice,status,userid,createtime) values ('${ordercode}',${orderdata[0].shopid},${orderdata[0].count},${orderdata[0].zprice},0,${orderdata[0].userid},'${createtime}')`;
return await query(sqlagain);
};
module.exports = {
AddOrder,
CheckOrders,
DeleteOrder,
UpdateOrderStatus,
Orderagain,
};
service/order.js
Koa provides a Response
object as the response
property of the Context
.
Koa's Response
object provides helpful methods for working with
http responses which delegate to a ServerResponse
.
Koa's pattern of delegating to Node's request and response objects rather than extending them
provides a cleaner interface and reduces conflicts between different middleware and with Node
itself as well as providing better support for stream handling. The IncomingMessage
can still be
directly accessed as the req
property on the Context
and ServerResponse
can be directly
accessed as the res
property on the Context
.
Here is an example using Koa's Response
object to stream a file as the response body.
var jwt = require("jsonwebtoken");
const signtoken = async (userdata) => {
return await jwt.sign(
{
data: userdata,
},
"asdfgh",
{
expiresIn: "2h",
}
);
};
module.exports = { signtoken };
extend/help.js
const Redis = require("ioredis");
const redis = new Redis();
module.exports = redis;
extend/redis.js
The Context
object also provides shortcuts for methods on its request
and response
. In the prior
examples, ctx.type
can be used instead of ctx.response.type
and ctx.accepts
can be used
instead of ctx.request.accepts
.
For more information on Request
, Response
and Context
, see the Request API Reference,
Response API Reference and Context API Reference.
Koa Application
The object created when executing new Koa()
is known as the Koa application object.
The application object is Koa's interface with node's http server and handles the registration of middleware, dispatching to the middleware from http, default error handling, as well as configuration of the context, request and response objects.
Learn more about the application object in the Application API Reference.
Documentation
Troubleshooting
Check the Troubleshooting Guide or Debugging Koa in the general Koa guide.
Running tests
$ npm test
Reporting vulnerabilities
To report a security vulnerability, please do not open an issue, as this notifies attackers of the vulnerability. Instead, please email dead_horse, jonathanong, and niftylettuce to disclose.
Authors
See AUTHORS.
Community
- Badgeboard and list of official modules
- Examples
- Middleware list
- Wiki
- Reddit Community
- Mailing list
- 中文文档 v1.x
- 中文文档 v2.x
- #koajs on freenode
Job Board
Looking for a career upgrade?
Backers
Support us with a monthly donation and help us continue our activities.
Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site.
License
5 months ago