繁体   English   中英

如何访问“?”后的GET参数在快递?

[英]How to access the GET parameters after "?" in Express?

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

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

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

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

我试过req.params.color但没有用。

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

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

例子:

GET /something?color1=red&color2=blue

然后在快递中,处理程序:

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

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

});

更新: req.param()现在已被弃用,所以以后不要使用这个答案。


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

在你的情况下:

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

从快速指南:

查找按以下顺序执行:

  • 请求参数
  • 请求体
  • 请求查询

请注意,该指南确实说明了以下内容:

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

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

查询字符串和参数不同。

您需要在单个路由 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

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

但只是为了更清楚:

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

req.queryreq.body将填充所有参数,无论它们是否在路由中。 当然,在查询字符串参数将在可用req.query和参数后身体会在提供req.body

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

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

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

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

});
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!')
)

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

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

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

您可以简单地使用req.query获取查询参数:

app.get('/', (req, res) => {
    let color1 = req.query.color1
    let color2 = req.query.color2
})

url模块提供用于 URL 解析和解析的实用程序。 不使用 Express 的 URL 解析:

const url = require('url');
const queryString = require('querystring');

let rawUrl = 'https://stackoverflow.com/?page=2&size=3';

let parsedUrl = url.parse(rawUrl);
let parse = queryString.parse(parsedUrl.query);

// parse = { page: '2', size: '3' }

其它的办法:

const url = require('url');

app.get('/', (req, res) => {
  const queryObject = url.parse(req.url,true).query;
});

url.parse(req.url,true).query返回{ color1: 'red', color2: 'green' }.
url.parse(req.url,true).host返回'localhost:8080'.
url.parse(req.url,true).search返回 '​​?color1=red&color2=green'。

只需使用app.get

app.get('/some/page/here', (req, res) => {
    console.log(req.query.color) // Your color value will be displayed
})

您可以在 expressjs.com 文档 api 上看到它: http ://expressjs.com/en/api.html

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM