如何在Express中的“?”之后访问GET参数?

问题描述 投票:448回答:8

我知道如何获得这样的查询的参数:

app.get('/sample/:id', routes.sample);

在这种情况下,我可以使用req.params.id来获取参数(例如2中的/sample/2)。

但是,对于像/sample/2?color=red这样的网址,如何访问变量color

我尝试了req.params.color,但它没有用。

node.js express query-string
8个回答
673
投票

因此,在检查了express reference之后,我发现req.query.color会给我回报我正在寻找的价值。

req.params是指URL中带有':'的项目,req.query是指与'?'相关联的项目

例:

GET /something?color1=red&color2=blue

然后在express中,处理程序:

app.get('/something', (req, res) => {
    req.query.color1 === 'red'  // true
    req.query.color2 === 'blue' // true
})

78
投票

使用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);

});

66
投票

更新:req.param()现已弃用,因此请继续使用此答案。


你的答案是首选的方法,但是我想我会指出你也可以使用req.param(parameterName, defaultValue)访问url,post和route参数。

在你的情况下:

var color = req.param('color');

从快递指南:

查找按以下顺序执行:

  • req.params
  • req.body
  • req.query

请注意,指南中说明了以下内容:

为了清楚起见,应该直接访问req.body,req.params和req.query - 除非您真正接受来自每个对象的输入。

然而在实践中,我实际上发现req.param()足够清晰,并使某些类型的重构更容易。


44
投票

@ Zugwait的回答是正确的。 req.param()已被弃用。你应该使用req.paramsreq.queryreq.body

但只是为了让它更清晰:

req.params将仅填充路线值。也就是说,如果你有像/users/:id这样的路线,你可以在idreq.params.id访问req.params['id']

req.queryreq.body将填充所有参数,无论他们是否在路线中。当然,查询字符串中的参数将在req.query中可用,并且帖子正文中的参数将在req.body中可用。

所以,回答你的问题,因为color不在路线中,你应该能够使用req.query.colorreq.query['color']获得它。


42
投票

查询字符串和参数不同。

您需要在单个路由URL中使用它们

请检查以下示例可能对您有用。

app.get('/sample/:id', function(req, res) {

 var id = req.params.id; //or use req.param('id')

  ................

});

获取传递第二段的链接是您的id示例:http://localhost:port/sample/123

如果您遇到问题,请使用'?'将传递变量用作查询字符串操作者

  app.get('/sample', function(req, res) {

     var id = req.query.id; 

      ................

    });

获取这个例子的链接:http://localhost:port/sample?id=123

两者都在一个例子中

app.get('/sample/:id', function(req, res) {

 var id = req.params.id; //or use req.param('id')
 var id2 = req.query.id; 
  ................

});

获取链接示例:http://localhost:port/sample/123?id=123


16
投票

快速手册说你应该使用req.query来访问QueryString。

// Requesting /display/post?size=small
app.get('/display/post', function(req, res, next) {

  var isSmall = req.query.size === 'small'; // > true
  // ...

});

7
投票
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!')
)

1
投票

我开始在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;

然后在您的控制器主体或快速请求链范围内的任何其他位置,您可以使用以下内容:

//./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);
});

这使得“钻研”用户可能已经发送了他们的请求的所有“自定义数据”变得非常方便。

注意

为什么'道具'领域?因为这是一个简化的片段,我在许多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";
    }
} 
© www.soinside.com 2019 - 2024. All rights reserved.