[英]Multiple get request loop -NODEjs /express/strava (cannot set headers after they are sent to the client )
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.我正在做一个学校项目,我正在使用 strava API 来获取用户活动和每个活动的流,虽然我正在使用一些库来执行此操作,但是当我尝试使用 for 循环获取所有活动流时,我得到这个错误不能在将标头发送到客户端后设置标头我知道我的代码有问题,但我还无法弄清楚。 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我不熟悉 strava api,但正如错误所说 - 您尝试多次发送响应
Do not call res.json() inside loop不要在循环内调用 res.json()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.