I have a list of users in a database. They have initially been given an access_token, when signing up to db, but as this expires I need to create a new access_token through a refresh_token which has also been saved in the db against a user.
I need to make a POST request to an endpoint to access get a new access token.
I am trying to loop over each row in the database and get a new access_token this way. When there is one user it works perfectly, but when there is more than one user in the users
array each user
is the same, i.e. the last user in the database table. I guess the request isn't finished and it is trying to send a new request or something like that.
Does anyone know how to get around this?
app.get('/get-users', function (req, res) {
connection.query('SELECT * from users', function(err, rows, fields) {
if(err) console.log(err);
for(var i = 0; i < rows.length; i++) {
name = rows[i].name;
userId = rows[i].userId;
console.log(userId);// this gives the correct userid
var authOptions = {
url: url,
headers: {
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
},
form: {
grant_type: 'refresh_token',
refresh_token: refresh_token
},
json: true
};
request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
var access_token = body.access_token;
users.push({name: name, userId: userId, accessToken: access_token});
console.log(userId)//gives last entry in db
}
});
setTimeout(function () {
console.log(users)
}, 3000)
}
});
res.send('getting here');
})