- Koa.js 教程
- Koa.js - 首页
- Koa.js - 概述
- Koa.js - 环境
- Koa.js - Hello World
- Koa.js - 生成器
- Koa.js - 路由
- Koa.js - URL构建
- Koa.js - HTTP方法
- Koa.js - 请求对象
- Koa.js - 响应对象
- Koa.js - 重定向
- Koa.js - 错误处理
- Koa.js - 级联
- Koa.js - 模板引擎
- Koa.js - 表单数据
- Koa.js - 文件上传
- Koa.js - 静态文件
- Koa.js - Cookie
- Koa.js - Session
- Koa.js - 身份验证
- Koa.js - 压缩
- Koa.js - 缓存
- Koa.js - 数据库
- Koa.js - RESTful APIs
- Koa.js - 日志记录
- Koa.js - 脚手架
- Koa.js - 资源
- Koa.js 有用资源
- Koa.js - 快速指南
- Koa.js - 有用资源
- Koa.js - 讨论
Koa.js - 请求对象
Koa Request 对象是 node 原生 request 对象的抽象层,它提供了日常 HTTP 服务器开发中很有用的附加功能。Koa request 对象嵌入在上下文对象 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://: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://:3000/hello/?name=Ayush&age=20&country=India 的请求上记录此内容,我们将得到以下对象。
{
name: 'Ayush',
age: '20',
country: 'India'
}
request.accepts(type)
此函数根据请求的资源是否接受给定的请求类型返回 true 或 false。
您可以在文档中阅读有关请求对象的更多信息:Request。
广告