javascript - 如何使用 koa-bodyparser 在 koa 中获取查询字符串?

标签 javascript node.js express koa

应用程序.js

var bodyParser = require('koa-bodyparser');

app.use(bodyParser());
app.use(route.get('/objects/', objects.all));

对象.js

module.exports.all = function * all(next) {
  this.body = yield objects.find({});
};

这适用于获取所有对象。但我想通过查询参数获取,类似于 localhost:3000/objects?city=Toronto How to use "city=Toronto"in my objects.js?

最佳答案

您可以使用 this.query 访问所有查询参数。

例如,如果请求来自 url /objects?city=Toronto&color=green,您将获得以下信息:

function * routeHandler (next) {
  console.log(this.query.city) // 'Toronto'
  console.log(this.query.color) // 'green'
}

如果你想访问整个查询字符串,你可以使用 this.querystring 代替。您可以在 docs 中阅读更多相关信息.


编辑:对于 Koa v2,您将使用 ctx.query 而不是 this.query

关于javascript - 如何使用 koa-bodyparser 在 koa 中获取查询字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41608891/

相关文章:

javascript - 从容器访问组件 `this`

javascript - 避免多次 onload 提交

node.js - 如何通过命令行设置 karma 配置条目?

javascript - 这段代码中定义了回调

javascript - 如何拦截 JSON Server 中的请求?

regex - 多个express的路由器使用根路径

javascript - jqGrid - 是否可以在初始化后设置 onSortCol?

javascript - 为什么不能在函数调用前使用前缀运算符?

javascript - 将不同对齐的 excel 转换为 json

javascript - 从 busboy 管道流到请求帖子