# 如何獲取query參數
routes/index.js
```javascript
var router = require('koa-router')();
router.get('/', function *(next) {
console.log(this.request.query)
console.log(this.query)
yield this.render('index', {
title: 'Hello World Koa!'
});
});
module.exports = router;
```
訪問http://127.0.0.1:3000/?a=1
日志
```
<-- GET /?a=1
{ a: '1' }
{ a: '1' }
```
和express里獲取query的方法是一樣的,req.query
koa里是
- this.request.query
- this.query
這里需要說明以下this上下文上有request和response2個對象,每次寫起來又比較麻煩
于是把request和response上的方法也丟給this,這樣就相當于this上有了對應request和response里的方法的別名(簡寫方式)
- 別名列表
Request aliases
以下訪問器和別名與 Request 等價:
- ctx.header
- ctx.method
- ctx.method=
- ctx.url
- ctx.url=
- ctx.originalUrl
- ctx.path
- ctx.path=
- ctx.query
- ctx.query=
- ctx.querystring
- ctx.querystring=
- ctx.host
- ctx.hostname
- ctx.fresh
- ctx.stale
- ctx.socket
- ctx.protocol
- ctx.secure
- ctx.ip
- ctx.ips
- ctx.subdomains
- ctx.is()
- ctx.accepts()
- ctx.acceptsEncodings()
- ctx.acceptsCharsets()
- ctx.acceptsLanguages()
- ctx.get()
Response aliases
以下訪問器和別名與 Response 等價:
- ctx.body
- ctx.body=
- ctx.status
- ctx.status=
- ctx.length=
- ctx.length
- ctx.type=
- ctx.type
- ctx.headerSent
- ctx.redirect()
- ctx.attachment()
- ctx.set()
- ctx.remove()
- ctx.lastModified=
- ctx.etag=
- Introduction
- Nodejs 4.x新特性
- classes
- typed arrays
- generators
- collections
- Set
- Map
- arrow functions
- block scoping
- template strings
- promises
- symbols
- Koa基礎
- 上下文
- koa-generator
- 安裝
- 創建項目
- 更改視圖模板引擎
- Routes
- HTTP
- Get
- 如何獲取query參數
- 如何獲取params
- Post
- 從post獲取參數
- 標準表單(Post with x-www-form-urlencoded)
- 文件上傳(Post with form-data)
- Post with raw
- 數據庫
- MySQL
- Mongo
- 流程控制
- generator/co
- es6的generator是什么?
- co = generator + promise
- async/await
- promise with bluebird
- 測試
- Mocha
- Supertest
- 部署
- 最佳實踐
- FAQ
- 如何發布本書到git pages
- 如何知道require模塊的用法
- koa中的異常處理