目录

Koa.js - 请求对象( Request Object)

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

提供所有请求标头。

request.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。

您可以在Request的文档中阅读有关请求对象的Request

↑回到顶部↑
WIKI教程 @2018