gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 00:16:57 30 4
gpt4 key购买 nike

应用程序.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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com