【问题标题】:how to pass query string and get object result in Express.js on Node.js?如何在 Node.js 上的 Express.js 中传递查询字符串并获取对象结果?
【发布时间】:2021-08-23 21:49:39
【问题描述】:

我在 nodeJs 中创建了我的 api 并表达,我想通过传递字符串参数来获取一个对象,但我无法获取这个对象。

这是我的应用

const express = require('express')
const app = express()

const produits = [
      {
         "codeProduit":"78",
         "nomCat":"nomCat11",
         "typeCat":"typeCat11"
      },
      {
         "codeProduit":"82",
         "nomCat":"nomCat21",
         "typeCat":"typeCat21"
      },
      {
         "codeProduit":"69",
         "nomCat":"nomCat31",
         "typeCat":"typeCat31"
      }
 ]


//http://localhost:3000/produits?codeProduit=78
app.get('/produits', (req, res) => {
    if(req.query.codeProduit != undefined && req.query.codeProduit != '') {
        res.json(produits[(req.query.codeProduit)])
    }  else {
        res.json(produits)
    }
     
 })
 
 app.get('/produits', (req, res) => {
      res.json(produits)
  })

  app.listen(3000,() => {
    console.log('Started on port 3000')
  })

我想得到这个对象

{
 "codeProduit":"78",
 "nomCat":"nomCat11",
 "typeCat":"typeCat11"
}

当我调用这个网址时:http://localhost:3000/produits?codeProduit=78

请问我该怎么做?

【问题讨论】:

    标签: node.js express query-string


    【解决方案1】:

    你在做 produits[78] 这是未定义的,所以你需要使用 find 来获得预期的产品

    app.get('/produits', (req, res) => {
      if (req.query.codeProduit != undefined && req.query.codeProduit != '') {
        const result = produits.find(p => p.codeProduit === req.query.codeProduit);
        result ? res.json(200).json(result) : res.status(404).json();
      } else {
        res.json(produits);
      }
    });
    

    【讨论】:

    • 嗨@tam.teixeira,感谢您的解决方案,它运作良好。现在,如果产品代码不存在或不正确,如何在 else 中管理错误情况。示例 localhost:3000/produits?codeProduit=76localhost:3000/produits?codeProduit=7
    • @lulu3131 我已经编辑了答案来处理它,它返回404 HTTP 状态代码。既然我回答了你的问题,请将其标记为已回答。
    猜你喜欢
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    相关资源
    最近更新 更多