文章目录
⭐前言
大家好,我是yma16,本文介绍node的一个web框架koa。
往期文章
node_windows环境变量配置
node_npm发布包
linux_配置node
node_nvm安装配置
node笔记_http服务搭建(渲染html、json)
node笔记_读文件
node笔记_写文件
node笔记_连接mysql实现crud
node笔记_formidable实现前后端联调的文件上传
⭐ koa框架是如何发展而来的?
关于node
关于express
关于Koa
⭐ koa框架的基本使用
💖 安装 koa
$ npm i koa
搭建一个hello csdn
const Koa = require('koa');
const app = new Koa();
// response
app.use(ctx => {
ctx.body = 'Hello csdn';
});
app.listen(3000);
ip默认localhost,访问localhost:3000成功返回hello csdn!
💖 koa的Middleware示例
koa有以下两种不同的函数作为中间件
- async function
- common function
async
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
记录请求的耗时
common
app.use((ctx, next) => {
const start = Date.now();
return next().then(() => {
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
});
这个时间差要比浏览器的响应时间小很多,浏览器的请求需要考虑到延迟等因素
💖 支持xml
定义一个名为designXml的xml文件
<?xml version="1.0" encoding="UTF-8"?>
<message>
<warning>
Hello csdn,I'm YMA16 and focus on front-end development.
</warning>
</message>
请求的body返回该xml文件
app.use(async (ctx, next) => {
await next();
ctx.response.type = 'xml';
ctx.response.body = fs.createReadStream('designXml.xml');
});
返回成功!
⭐ 结束
本文介绍koa到此结束,如有错误或者不足欢迎指出!
💖 感谢你的阅读 💖