如何使用请求模块使用id获取特定项目

时间:2015-06-23 08:43:10

标签: javascript node.js rest express request

我最终想要从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) });
  }
});

1 个答案:

答案 0 :(得分:0)

如果我的服务器根据他/她的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');
});

然后我会使用我的服务器在路由1中传递/users/:userId的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' } }
});