【问题标题】:how to GET specific item using id using request module如何使用请求模块使用 id 获取特定项目
【发布时间】:2015-06-23 08:43:10
【问题描述】:

我最终想从 RESTful Web 服务获取特定的 id,对其进行修改并将其放回(更新)。下面的代码从 Web 服务中获取所有内容,我如何修改它以获取特定的 id?

request({
  url: url,                                        // URL to hit
  qs: { from: 'blog example', time: +new Date() }, // Query string data
  method: 'GET',                                   // Specify the method
}, function(error, response, body) {
  if (error) {
    res.render('index', { title: 'Express', data: []});
  } else {
    console.log(body);
    res.render('index', { title: 'Express', data: JSON.parse(body) });
  }
});

【问题讨论】:

    标签: javascript node.js rest express request


    【解决方案1】:

    如果我的服务器根据他/她的 id 返回用户:

    var express = require('express');
    var app = express();
    
    var users = [
      {id: 1, name: 'wilson'},
      {id: 2, name: 'santiago'}
    ];
    
    app.get('/users/:userId', function(req, res) {
      var userId = Number(req.params.userId);
      var userFound = null;
    
      users.map(function(user) {
        if (user.id === userId) {
          userFound = user;
        }
      });
    
      res.send({user: userFound});
    });
    
    app.listen(4040, function() {
      console.log('server up and running at 4040');
    });
    

    然后我会在路由/users/:userId 中通过1 的ID 消耗我的服务器:

    var request = require('request');
    var URL_SERVER = 'http://localhost:4040';
    var URL = URL_SERVER + '/users/1';
    
    request({
      url: URL,
      method: 'GET'
    }, function(err, response, body) {
      var result = JSON.parse(body);
    
      // getting only the user with the id of 1.
      console.log(result); // { user: { id: 1, name: 'wilson' } }
    });
    

    【讨论】:

      猜你喜欢
      • 2020-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-15
      • 1970-01-01
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      相关资源
      最近更新 更多