node.js 如何访问“?”后的GET参数 在快递?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17007997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access the GET parameters after "?" in Express?
提问by Hanfei Sun
I know how to get the params for queries like this:
我知道如何为这样的查询获取参数:
app.get('/sample/:id', routes.sample);
In this case, I can use req.params.idto get the parameter (e.g. 2in /sample/2).
在这种情况下,我可以使用req.params.id来获取参数(例如2in /sample/2)。
However, for url like /sample/2?color=red, how can I access the variable color?
但是,对于 url like /sample/2?color=red,我如何访问变量color?
I tried req.params.colorbut it didn't work.
我试过了,req.params.color但没有用。
回答by Hanfei Sun
So, after checking out the express reference, I found that req.query.colorwould return me the value I'm looking for.
所以,在检查了express 引用之后,我发现它req.query.color会返回我正在寻找的值。
req.params refers to items with a ':' in the URL and req.query refers to items associated with the '?'
req.params 指的是 URL 中带有“:”的项目,而 req.query 指的是与“?”相关联的项目
Example:
例子:
GET /something?color1=red&color2=blue
Then in express, the handler:
然后在快递中,处理程序:
app.get('/something', (req, res) => {
req.query.color1 === 'red' // true
req.query.color2 === 'blue' // true
})
回答by satyam kumar
Use req.query, for getting he value in query string parameter in the route. Refer req.query. Say if in a route, http://localhost:3000/?name=satyamyou want to get value for name parameter, then your 'Get' route handler will go like this :-
使用 req.query,获取路由中查询字符串参数的值。请参阅req.query。假设在一个路由中,http://localhost:3000/?name=satyam你想获取 name 参数的值,那么你的“Get”路由处理程序会像这样:-
app.get('/', function(req, res){
console.log(req.query.name);
res.send('Response send to client::'+req.query.name);
});
回答by Zugwalt
Update:req.param()is now deprecated, so going forward do not use this answer.
更新:req.param()现在已弃用,因此以后不要使用此答案。
Your answer is the preferred way to do it, however I thought I'd point out that you can also access url, post, and route parameters all with req.param(parameterName, defaultValue).
您的回答是首选方法,但我想我想指出的是,您还可以使用req.param(parameterName, defaultValue).
In your case:
在你的情况下:
var color = req.param('color');
From the express guide:
从快速指南:
lookup is performed in the following order:
- req.params
- req.body
- req.query
查找按以下顺序执行:
- 请求参数
- 请求体
- 请求查询
Note the guide does state the following:
请注意,该指南确实说明了以下内容:
Direct access to req.body, req.params, and req.query should be favoured for clarity - unless you truly accept input from each object.
为了清楚起见,应该支持直接访问 req.body、req.params 和 req.query - 除非您真正接受来自每个对象的输入。
However in practice I've actually found req.param()to be clear enough and makes certain types of refactoring easier.
然而在实践中,我发现它已经req.param()足够清晰,并且使某些类型的重构更容易。
回答by Raja Rama Mohan Thavalam
Query string and parameters are different.
查询字符串和参数不同。
You need to use both in single routing url
您需要在单个路由 url 中使用两者
Please check below example may be useful for you.
请检查以下示例可能对您有用。
app.get('/sample/:id', function(req, res) {
var id = req.params.id; //or use req.param('id')
................
});
Get the link to pass your second segment is your id example: http://localhost:port/sample/123
获取传递第二段的链接是您的 id 示例:http://localhost:port/sample/123
If you facing problem please use Passing variables as query string using '?' operator
如果您遇到问题,请使用传递变量作为查询字符串使用 '?' 操作员
app.get('/sample', function(req, res) {
var id = req.query.id;
................
});
Get link your like this example: http://localhost:port/sample?id=123
获取你喜欢这个例子的链接:http://localhost:port/sample?id=123
Both in a single example
都在一个例子中
app.get('/sample/:id', function(req, res) {
var id = req.params.id; //or use req.param('id')
var id2 = req.query.id;
................
});
Get link example: http://localhost:port/sample/123?id=123
回答by André Pena
@Zugwait's answer is correct. req.param()is deprecated. You should use req.params, req.queryor req.body.
@Zugwait 的回答是正确的。req.param()已弃用。您应该使用req.params,req.query或req.body。
But just to make it clearer:
但只是为了更清楚:
req.paramswill be populated with only the route values. That is, if you have a route like /users/:id, you can access the ideither in req.params.idor req.params['id'].
req.params将仅填充路由值。也就是说,如果您有类似 的路线/users/:id,则可以访问idinreq.params.id或req.params['id']。
req.queryand req.bodywill be populated with allparams, regardless of whether or not they are in the route. Of course, parameters in the query string will be available in req.queryand parameters in a post body will be available in req.body.
req.query并且req.body将填充所有参数,无论它们是否在路线中。当然,查询字符串中的req.query参数将在req.body.
So, answering your questions, as coloris not in the route, you should be able to get it using req.query.coloror req.query['color'].
因此,回答您的问题,因为color不在路线中,您应该能够使用req.query.color或来获得它req.query['color']。
回答by Jan Biasi
回答by seme
const express = require('express')
const bodyParser = require('body-parser')
const { usersNdJobs, userByJob, addUser , addUserToCompany } = require ('./db/db.js')
const app = express()
app.set('view engine', 'pug')
app.use(express.static('public'))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.get('/', (req, res) => {
usersNdJobs()
.then((users) => {
res.render('users', { users })
})
.catch(console.error)
})
app.get('/api/company/users', (req, res) => {
const companyname = req.query.companyName
console.log(companyname)
userByJob(companyname)
.then((users) => {
res.render('job', { users })
}).catch(console.error)
})
app.post('/api/users/add', (req, res) => {
const userName = req.body.userName
const jobName = req.body.jobName
console.log("user name = "+userName+", job name : "+jobName)
addUser(userName, jobName)
.then((result) => {
res.status(200).json(result)
})
.catch((error) => {
res.status(404).json({ 'message': error.toString() })
})
})
app.post('/users/add', (request, response) => {
const { userName, job } = request.body
addTeam(userName, job)
.then((user) => {
response.status(200).json({
"userName": user.name,
"city": user.job
})
.catch((err) => {
request.status(400).json({"message": err})
})
})
app.post('/api/user/company/add', (req, res) => {
const userName = req.body.userName
const companyName = req.body.companyName
console.log(userName, companyName)
addUserToCompany(userName, companyName)
.then((result) => {
res.json(result)
})
.catch(console.error)
})
app.get('/api/company/user', (req, res) => {
const companyname = req.query.companyName
console.log(companyname)
userByJob(companyname)
.then((users) => {
res.render('jobs', { users })
})
})
app.listen(3000, () =>
console.log('Example app listening on port 3000!')
)
回答by Lee Brindley
A nice technique i've started using with some of my apps on express is to create an object which merges the query, params, and body fields of express's request object.
我在 express 上的一些应用程序中开始使用的一个很好的技术是创建一个对象,该对象合并 express 请求对象的查询、参数和正文字段。
//./express-data.js
const _ = require("lodash");
class ExpressData {
/*
* @param {Object} req - express request object
*/
constructor (req) {
//Merge all data passed by the client in the request
this.props = _.merge(req.body, req.params, req.query);
}
}
module.exports = ExpressData;
Then in your controller body, or anywhere else in scope of the express request chain, you can use something like below:
然后在您的控制器主体或快速请求链范围内的任何其他地方,您可以使用以下内容:
//./some-controller.js
const ExpressData = require("./express-data.js");
const router = require("express").Router();
router.get("/:some_id", (req, res) => {
let props = new ExpressData(req).props;
//Given the request "/592363122?foo=bar&hello=world"
//the below would log out
// {
// some_id: 592363122,
// foo: 'bar',
// hello: 'world'
// }
console.log(props);
return res.json(props);
});
This makes it nice and handy to just "delve" into all of the "custom data" a user may have sent up with their request.
这使得“深入研究”用户可能随其请求发送的所有“自定义数据”变得非常方便。
Note
笔记
Why the 'props' field? Because that was a cut-down snippet, I use this technique in a number of my APIs, I also store authentication / authorisation data onto this object, example below.
为什么是“道具”领域?因为这是一个精简的片段,我在我的许多 API 中使用了这种技术,我还将身份验证/授权数据存储到这个对象上,示例如下。
/*
* @param {Object} req - Request response object
*/
class ExpressData {
/*
* @param {Object} req - express request object
*/
constructor (req) {
//Merge all data passed by the client in the request
this.props = _.merge(req.body, req.params, req.query);
//Store reference to the user
this.user = req.user || null;
//API connected devices (Mobile app..) will send x-client header with requests, web context is implied.
//This is used to determine how the user is connecting to the API
this.client = (req.headers) ? (req.headers["x-client"] || (req.client || "web")) : "web";
}
}

