Here is my global array with json in my users.js:
global.users = [
{
'id':1,
'name' : 'Dain',
'age' : 24,
'hobby' : 'gaming'
}
];
The router.get function:
router.get('/:userid', function(req, res){
for(let i = 0 ; i < global.users.length ; i++){
if(global.users[i].id === parseInt(req.params.userid, 10)){
return res.json({
user: global.users[i],
message : 'Success',
error: false
});
}
}
return res.status(404).json({
message : 'User Not Found',
error: true
});
});
However, the following function for getting two params does not work as expected:
router.get("'/:userid'+'+:age'", function(req, res){
for(let i = 0 ; i < global.users.length ; i++){
if( (global.users[i].id === parseInt(req.params.userid, 10)) && (global.users[i].age === parseInt(req.params.age, 10))){
return res.json({
user: global.users[i],
message : 'Success',
error: false
});
}
}
return res.status(404).json({
message : 'User Not Found',
error: true
});
});
Even if I pass age as follows in the url, it still returns the user info.
http://localhost:8080/users/1+226
Since 226 is not any of the ages defined, it must return:
{
message : 'User Not Found',
error: true
}
Even if I put any age, it still returns the values. Please guide.
http://localhost:8080/users/1+24
instead of creating a loop that check if the specific fields matches. use underscoreJS it is better in finding data inside array http://underscorejs.org/#findWhere
Note: (Install module underscore first)
var _ = require('underscore');
var user = _.findWhere(global.users, {
id: req.params.userid,
age: req.params.age
});
if (user !== null) {
return res.json({
user: user,
message : 'Success',
error: false
});
} else {
return res.status(404).json({
message : 'User Not Found',
error: true
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.