Javascript 如何使用请求模块使用id获取特定项目
我最终希望从RESTful web服务中获得一个特定的id,修改它并将其放回(更新)。下面的代码从web服务获取所有信息,我如何修改它以获得特定的idJavascript 如何使用请求模块使用id获取特定项目,javascript,node.js,rest,express,request,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',
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) });
}
});
如果我的服务器根据用户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' } }
});