I am working on a school project and I am using the strava API to get users activities and streams for each activity, I am though using some libraries to do this but when I try to get all activities streams using for loop I get this error cannot set headers after they are sent to the client I know there's something wrong with my code but I can't figure it out yet. If you have a better way to do this please enlighten me.
Here's the code:
router.get('/streams/:id', (req, res,done) => {
const userc = req.user;
const access_token = userc.access_token;
var _ = require("underscore");
var fs = require("fs");
const ids = [5312632886,
5307798051,
5301826997,
5301821600,
5283410624,
3477443042]
for (let i = 0; i < ids.length ; i++) {
strava = new stravaApi.client(access_token);
strava.streams.activity({
id: ids[i],
types: 'time,heartrate,velocity_smooth,altitude,distance,latlng,cadence,watts,temp,moving,grade_smooth,average_speed',
resolution: 'high'
}, function (err, payload) {
if (!err) {
res.json(payload)
console.log(payload)
fs.writeFile("activity-streams.json", JSON.stringify(payload), err => {
if (err) throw err;
console.log("Done writing"); // Success
});
} else {
console.log(err)
}
})
}
})
I am not familiar with strava api, but as error says - you try to send response multiple times
Do not call res.json() inside loop