Koa.js - 请求对象

Koa Request对象是节点的vanilla请求对象之上的抽象,提供了对日常HTTP服务器开发有用的附加功能. Koa请求对象嵌入在上下文对象中, this .每当我们收到请求时,让我们注销请求对象.

var koa = require('koa');
var router = require('koa-router');
var app = koa();

var _ = router();

_.get('/hello', getMessage);

function *getMessage(){
   console.log(this.request);
   this.body = 'Your request has been logged.';
}
app.use(_.routes());
app.listen(3000);

当您运行此代码并导航到 https://localhost:3000/hello 时,您将收到以下回复.

请求对象

在您的控制台上,您将获得请求对象已注销.

{ 
   method: 'GET',
   url: '/hello/',
   header: 
   { 
      host: 'localhost:3000',
      connection: 'keep-alive',
      'upgrade-insecure-requests': '1',
      'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) 
         AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
      accept: 'text/html,application/xhtml+xml,
         application/xml;q = 0.9,image/webp,*/*;q = 0.8',
      dnt: '1',
      'accept-encoding': 'gzip, deflate, sdch',
      'accept-language': 'en-US,en;q = 0.8' 
   }
}

我们可以使用此对象访问请求的许多有用属性.让我们看一些例子.

request.header

提供所有请求标题.

请求.method

提供请求方法(GET,POST等)

request.href

提供完整的请求URL.

request.path

提供请求的路径.没有查询字符串和基本URL.

request.query

提供已解析的查询字符串.例如,如果我们在 https://localhost:3000/hello/?name = Ayush& age = 20& country = India 等请求上记录此信息,那么我们将获得以下对象.

{
   name: 'Ayush',
   age: '20',
   country: 'India'
}

request.accepts(type)

此函数返回true或false基于请求的资源是否接受给定的请求类型.