首页 > 技术文章 > koa2笔记

theblogs 2019-03-19 15:43 原文

Koa -- 基于 Node.js 平台的下一代 web 开发框架

首先创建一个项目文件夹进行初始化

npm init -y

该命令执行后会生成一个package.json项目描述文件

安装koa

npm install koa --save

该命令执行后会生成node_modules文件夹(用来存放一些npm安装的依赖包)

在项目文件夹中新建一个app.js文件

const koa = require('koa');//引包
const app = new Koa();

app.use(async(ctx)=>{
    ctx.body = 'hello world';//把输出的返回给前台
})
app.listen(3000)//监听端口

输入 node app.js ,按tab补全 回车,输入http://localhost:3000,这个服务就会跑起来

 

对于每一个http请求,koa将调用我们传入的异步函数来处理

async (ctx, next) => {
    await next();
    // 设置response的Content-Type:
    ctx.response.type = 'text/html';
    // 设置response的内容:
    ctx.response.body = '<h1>Hello, 2019</h1>';
}
/*
这里的ctx是由koa传入的封装了request和response的变量,我们可以通过他来访问request和response
这里的next是koa传入的将要处理的下一个异步函数
上面的异步函数中,我们首先用await next();处理下一个异步函数,然后,设置response的Content-Type和内容
*/

Context 对象(简写ctx),表示一次对话的上下文(包括请求和回复),通过加工这个对象,就可以控制返回给用户的内容

 

由async标记的函数称为异步函数,在异步函数中,可以用await调用另一个异步函数

ctx对象中有一些简写的方法:

//ctx.url相当于ctx.request.url

//ctx.type相当于ctx.response.type

 

get请求 

 
const Koa = require('koa');
const app = new Koa();
app.use(async(ctx)=>{
    let url =ctx.url;
    let request =ctx.request;
    let req_query = request.query;//返回的是格式化好的参数对象
    let req_querystring = request.querystring;//返回的是请求字符串
    ctx.body={
        url,
        req_query,
        req_querystring
    }
});
app.listen(3000,()=>{
    console.log('server is starting at port 3000');
});

 

在koa2中GET请求通过ctx.request接收,但是接受的方法有两种:query和querystring

query返回的是格式化好的参数对象

ctx.request.query  -> {key:val}

querystring返回的是请求字符串

ctx.request.querystring -> key=val&key=val //字符串 (查询信息,不包括问号)

栗子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    用户名:<input type="text" id="user">
    年龄:<input type="text" id="age"> 
    <button id="btn">提交</button>
    <script>
    //get请求
    btn.onclick = function(){
        let obj = {
            user:user.value,
            age:age.value
        }
        fetch('/users?'+new URLSearchParams(obj).toString())
        .then(d=>d.json())
        .then(d=>{
            console.log(d);
        })
    }
    </script>
</body>
</html>

 

const koa = require('koa');
const app = new koa();
const router = require('koa-router')();
const static = require('koa-static');
const path = require('path');

let sql = [
    {
        name:'yi',
        age:22
    },
    {
        name:'er',
        age:23
    },
    {
        name:'san',
        age:20
    },
    {
        name:'si',
        age:20
    }
];
//user=jin&age=18 接口
   
router.get('/users',async(ctx)=>{
    
    // console.log(ctx.query)
    let mybody = ctx.query;
    console.log(mybody)
    let resobj = {code:0,msg:'成功'};
    let exist = sql.find((e)=>mybody.user == e.name)
    if(exist){
        resobj.code = 1;
        resobj.msg = '已经有了';
    }
    else{
        sql.push({
            name:mybody.user,
            age:mybody.age
        })
    }
    ctx.body = resobj;

})

app.use(static(path.join(__dirname,'www')))
app.use(router.routes())
app.listen(2019,()=>{
    console.log('已经启动服务器')
})

 

总结:

获得GET请求的方式有两种,一种是从request中获得,一种是一直从上下文中获得。

获得的格式也有两种:query和querystring

 

post请求

ctx.request与ctx.req之间的区别
前者从request中获取get请求,后者从上下文中直接获取
ctx.request是Koa2中context经过封装的请求对象,用起来更直观和简单
ctx.req是context提供的node.js原生HTTP请求对象
 
post请求时候可以使用 bodyParser 中间件
 
安装中间件
npm i koa-bodyparser -S

引包 使用

const bodyparser = require('koa-bodyparser');
app.use(bodyparser());

 

栗子
//post请求
    btn.onclick = function(){
        let obj = {
            user:user.value,
            age:age.value
        }
        fetch('/users',{
            method:'post',
            headers:{'Content-Type':'application/x-www-form-urlencoded'},
            body:new URLSearchParams(obj).toString()
        })
        .then(d=>d.json())
        .then(d=>{
            console.log(d);
        })
 }
const koa = require('koa');
const app = new koa();
const router = require('koa-router')();
const static = require('koa-static');
const bodyParser = require('koa-bodyparser');
const path = require('path');

let sql = [
    {
        name:'yi',
        age:22
    },
    {
        name:'song',
        age:23
    }
];
   
router.post('/users',async(ctx)=>{
    
    // console.log(ctx.query)
    let mybody = ctx.request.body;
    console.log(mybody)
    let resobj = {code:0,msg:'成功'};
    let exist = sql.find((e)=>mybody.user == e.name)
    if(exist){
        resobj.code = 1;
        resobj.msg = '已经有了';
    }
    else{
        sql.push({
            name:mybody.user,
            age:mybody.age
        })
    }
    ctx.body = resobj;

})

app.use(bodyParser())
app.use(static(path.join(__dirname,'www')))
app.use(router.routes())
app.listen(2019,()=>{
    console.log('已经启动服务器')
})

 

get请求使用ctx.query,post请求使用ctx.body 

 

路由

安装router(才能写接口)

npm i koa-router -S

引包

const router = require('koa-router')()

get方式(两种写法)

//第一种
router.get('/user',async(ctx)=>{
    //这里面放get请求的逻辑
})
/*
第二种,在一个单独的文件里边写get请求的逻辑,在这里需要require引一下
*/
router.get('/user',require('../xxx'))

use引用

app.use(router.routes());

 

静态资源

安装

npm i koa-static -S

引入包

const static = require('koa-static');
const path = require('path');

使用static中间件,设置静态资源的目录

//路径指向 当前目录www
app.use(static(
    path.join(__dirname,'www')
)) 

 

推荐阅读