【问题标题】:Sending only some data in a GET request在 GET 请求中仅发送一些数据
【发布时间】:2017-10-21 06:09:47
【问题描述】:

基本上,当我向我的 REST API 发出 GET 请求时,我只想发回一些数据。我的 GET 请求代码:

router.get('/user/all', function(req, res, next){
    User.find({name: req.query.name}).then(function(assets){
        res.send(assets);
    });
});

返回:

[
  {
    "_id": "546b454b5634563b546",
    "name": "John Doe",
    "email": "johndoe@johndoe.com",
    "phoneNo": "00000000000",
    "active": true,
    "__v": 0,
    "assets": [
      {
        "name": "house",
        "location": {
          "_id": "592190ce29f12e179446d837",
          "coordinates": [
            -81.5,
            24.1
          ],
          "type": "point"
        },
        "_id": "592190ce29f12e179446d836"
      }
    ]
  }
]

但我只希望它返回:

[
   {
     "name": "house",
     "location": {
     "_id": "592190ce29f12e179446d837",
     "coordinates": [
       -81.5,
        24.1
      ],
      "type": "point"
    },
    "_id": "592190ce29f12e179446d836"
  }
]

如何更改 API 请求以实现此目的?

谢谢

【问题讨论】:

    标签: javascript node.js rest api web


    【解决方案1】:

    如果您只想退回资产,请尝试以下操作:

    router.get('/user/all', function(req, res, next){
        User.find({name: req.query.name}).then(function(assets){
            res.send(assets.map(function(x) {return x.assets;}))
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2016-08-04
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-21
      • 2021-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多