Koa.js - Request 请求对象
Koa Request 请求对象是节点原始请求对象之上的抽象,提供对日常 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 文档中阅读有关请求对象的更多信息。

