本文共 5534 字,大约阅读时间需要 18 分钟。
Koa 由 Express 团队设计,是 Express 的下一代Web框架,旨在为 Web 应用和 API 开发提供更小、更灵活、更稳健的基础。通过利用异步功能,Koa 消除了回调的痛点,提升了错误处理能力,避免了回调地狱问题。与 Express不同,Koa 不绑定任何中间件,而是提供了一套优雅的方法,帮助开发者快速而愉快地编写服务端应用程序。
mkdir koa_testcd koa_testnpm i koa
app.jsconst Koa = require('koa');const app = new Koa();app.use(async ctx => { ctx.body = 'Hello World';});app.listen(3000); node app.js
打开浏览器访问 http://localhost:3000/,即可看到 "Hello World"。
npm i koa-router
const Koa = require('koa');const Router = require('koa-router');const app = new Koa();const router = new Router();router.get('/hello', (ctx) => { ctx.body = 'Hello World';});app.use(router.routes()).use(router.allowedMethods());app.listen(3000); const Koa = require('koa');const Router = require('koa-router');const app = new Koa();const router = new Router();router.get('/hello/:name', (ctx) => { ctx.body = 'Hello World,' + ctx.params.name;});app.use(router.routes()).use(router.allowedMethods());app.listen(3000); 访问 http://localhost:3000/hello/zhangshan,将显示 "Hello World,zhangshan"。
router.get('/hello', (ctx) => { ctx.body = 'Hello World,' + ctx.query.name;}); 访问 http://localhost:3000/hello?name=zhangshan,将显示 "Hello World,zhangshan"。
需要安装 koa-body:
npm i koa-body
const Koa = require('koa');const Router = require('koa-router');const bodyParser = require('koa-body');const app = new Koa();const router = new Router();app.use(bodyParser());router.post('/hello', (ctx) => { ctx.body = 'Hello World,' + ctx.request.body.name;});app.use(router.routes()).use(router.allowedMethods());app.listen(3000); 使用 Postman 或 curl 发送 POST 请求:
curl -d '{"name":"zhangshan"}' -H "Content-Type: application/json" -X POST http://127.0.0.1:3000/hello 响应将显示 "Hello World,zhangshan"。
router.post('/hello', (ctx) => { const { name } = ctx.request.body; const res = '[' + name + ']'; ctx.response.status = 200; ctx.response.body = 'Hello World,' + res;}); 发送 POST 请求,响应将显示 "Hello World,[zhangshan]"。
router.post('/hello', (ctx) => { const { name } = ctx.request.body; if (!name) { const err = new Error('name required'); err.status = 400; err.expose = true; throw err; } const res = '[' + name + ']'; ctx.response.status = 200; ctx.response.body = 'Hello World,' + res;}); 发送没有 name 属性的 POST 请求,响应将显示 "name required",状态码为 400。
app.on('error', (err) => { console.error('server error:', err);}); 用于打印请求日志:
const KoaLogger = require('koa-logger');app.use(KoaLogger((str, args) => { logger.debug(str);})); 用于发送 HTTP 请求:
const koaRequest = require('koa-http-request');app.use(koaRequest({ json: true, timeout: 3000, host: 'www.baidu.com'}));const result = await ctx.get('/');console.log(result); 用于生成 Swagger UI:
const koaSwagger = require('koa2-swagger-ui');app.use(koaSwagger({ routePrefix: '/swagger', swaggerOptions: { url: '/api-docs.json', hideTopbar: true }})); 用于设置跨域:
const convert = require('koa-convert');const cors = require('koa2-cors');app.use(convert(cors({ allowMethods: ['GET', 'POST', 'PUT', 'DELETE'], allowHeaders: ['Content-Type', 'Accept'], origin: ctx => '*'}))); 用于 gzip 压缩:
const compress = require('koa-compress');app.use(compress({ threshold: 2048, flush: require('zlib').Z_SYNC_FLUSH})); ctx.header:获取请求头对象ctx.headers:设置请求头对象ctx.method:获取或设置请求方法ctx.url:获取或设置请求 URLctx.originalUrl:获取原始 URLctx.origin:获取主机名和端口ctx.href:获取完整 URLctx.path:获取或设置路径ctx.query:获取或设置查询参数ctx.querystring:获取或设置原始查询字符串ctx.host:获取主机名ctx.hostname:获取主机名ctx.fresh:检查请求是否为"fresh"ctx.stale:检查请求是否为"stale"ctx.socket:获取 Socket 对象ctx.protocol:获取协议(http 或 https)ctx.secure:判断是否使用 HTTPSctx.ip:获取远程 IPctx.ips:获取 X-Forwarded-For IPctx.subdomains:获取子域名ctx.is():判断内容类型ctx.accepts():判断支持的内容类型ctx.body:获取或设置响应体ctx.status:获取或设置状态码ctx.message:获取或设置状态消息ctx.length:获取或设置内容长度ctx.type:获取或设置内容类型ctx.headerSent:检查响应头是否已发送ctx.redirect():进行重定向ctx.attachment():提示下载ctx.set():设置多个响应头字段ctx.append():添加响应头字段ctx.remove():移除响应头字段ctx.lastModified:获取最后修改时间ctx.lastModified:设置最后修改时间ctx.etag:设置 ETag以下是 Koa 支持的所有状态码及其对应的文字描述:
100 continue101 switching protocols102 processing200 ok201 created202 accepted203 non-authoritative information204 no content205 reset content206 partial content207 multi-status208 already reported226 im used300 multiple choices301 moved permanently302 found303 see other304 not modified305 use proxy307 temporary redirect308 permanent redirect400 bad request401 unauthorized402 payment required403 forbidden404 not found405 method not allowed406 not acceptable407 proxy authentication required408 request timeout409 conflict410 gone411 length required412 precondition failed413 payload too large414 uri too long415 unsupported media type416 range not satisfiable417 expectation failed418 I'm a teapot422 unprocessable entity423 locked424 failed dependency426 upgrade required428 precondition required429 too many requests431 request header fields too large500 internal server error501 not implemented502 bad gateway503 service unavailable504 gateway timeout505 http version not supported506 variant also negotiates507 insufficient storage508 loop detected510 not extended511 network authentication required
转载地址:http://pfib.baihongyu.com/