Koa2学习(三)GET请求

Koa2学习(三)GET请求

GET请求是前后端交互最常用的请求之一,常常用来进行查询操作。
那么Koa是如何接收并处理GET请求呢?

创建一个服务

// 引入Koa
const Koa = require('koa')
const app = new Koa()
app.use(async ctx => {
    ctx.body = 'Hello World'
})
app.listen(8000)

module.exports = app
  1. 其中ctx是Koa2非常重要的一个上下文对象,可以把它理解为一个全局的顶层对象,Koa2里面绝大部分的属性和方法都可以通过ctx对象获取。
  2. 其中ctx.body就是返回的html内容。
  3. app.listen(...)是koa2的一个语法糖,等于运行了下面这两个方法,实质就是调用http模块创建一个监听端口的服务。
  4. 每收到一个http请求,koa就会调用通过app.use()注册的async函数,并传入ctx和next参数。
const http = require('http');
http.createServer(app.callback()).listen(...);

接收请求

koa2每一个请求都会被传入到app.use()方法中,app.use会把请求信息放入到ctx中,我们可以从ctx中获取请求的基本信息。

app.use(async ctx => {
    const url = ctx.url // 请求的url
    const method = ctx.method   // 请求的方法
    const query = ctx.query // 请求参数
    const querystring = ctx.querystring // url字符串格式的请求参数
    ctx.body = {
        url,
        method,
        query,
        querystring,
    }
})

现在访问localhost:8000?username=zj可以看到浏览器返回

{
    "url": "/?username=zj",
    "method": "GET",
    "query": {
        "username": "zj"
    },
    "querystring": "username=zj"
}

请求url是/?username=zj,请求方法是GET,请求参数是username=zj

ctx还有一个request对象,是http请求对象,我们也可以从ctx.request中获取上面的参数。

app.use(async ctx => {
    const req = ctx.request
    const url = req.url // 请求的url
    const method = req.method   // 请求的方法
    const query = req.query // 请求参数
    const querystring = req.querystring // url字符串格式的请求参数
    ctx.body = {
        url,
        method,
        query,
        querystring,
        req,
    }
})

浏览器访问结果:

{
    "url": "/?username=zj",
    "method": "GET",
    "query": {
        "username": "zj"
    },
    "querystring": "username=zj",
    "req": {
        "method": "GET",
        "url": "/?username=zj",
        "header": {
            "host": "localhost:8000",
            "connection": "keep-alive",
            "cache-control": "max-age=0",
            "upgrade-insecure-requests": "1",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            "accept-encoding": "gzip, deflate, br",
            "accept-language": "zh-CN,zh;q=0.9",
            "cookie": "_ga=GA1.1.1379681827.1520244125"
        }
    }
}

总结

  1. 我们通过app.use()方法,接收并处理http GET请求。
  2. 通过app.use()中传入async方法的ctx对象或者ctx.request获取到请求信息。

猜你喜欢

转载自www.cnblogs.com/shenshangzz/p/9973381.html