如何在每个循环中更改请求 url?
How can I change request url by every each loop?
我正在尝试使用 request
和 cheerio
.
从 post 参数的链接中获取每个视频的 src
要获取每个视频的 src,我应该在每个循环中更改请求选项的 url。但是当我尝试获取类似下面代码的 src 时,更改请求的 url 比请求更快,因此更改请求的 url 是在请求完成之前完成的。我可以做些什么来实现我想要的?
这是代码
let opt = {
transform: function(body) {
return cheerio.load(body);
}
};
router.post('/api', function(req, res) {
let idArray = req.body.data;
for(var i=0; i<idArray.length; i++) {
opt.uri = baseURL + idArray[i];
request(opt)
.then(function($) {
console.log($('video').src);
}
日志(它打印同样的东西)
https://example.mp4/asdfasdf
https://example.mp4/asdfasdf
编辑
当我使用这段代码时,我从 idArray[i]
得到 undefined
for(var i=0; i<idArray.length; i++) {
console.log("Before", baseURL + idArray[i])
rpap(baseURL + idArray[i])
.then(function($) {
console.log(idArray);
console.log("After", baseURL + idArray[i]);
}
日志
before http://example.com/adsfasdf
before http://example.com/famvvasd
after http://example.com/undefined
after http://example.com/undefined
为什么不将新的 uri 与全局选项对象合并?我建议不要更改全局选项对象,因为可以发出多个请求并且可以以意想不到的方式更改道具。
for (var i = 0; i < idArray.length; i++) {
let uri = baseURL + idArray[i];
request({
...opt,
uri // expands to uri: uri as per es6 style
})
.then(function($) {
console.log($('video').src);
})
}
此外,如果您总是使用转换选项,则可以将其设置为默认值。使用 request-promise 它看起来像这样(来自他们的文档):
var rpap = rp.defaults({ transform: autoParse });
rpap('http://google.com')
.then(function (autoParsedBody) {
// :)
});
rpap('http://echojs.com')
.then(function (autoParsedBody) {
// =)
});
我正在尝试使用 request
和 cheerio
.
要获取每个视频的 src,我应该在每个循环中更改请求选项的 url。但是当我尝试获取类似下面代码的 src 时,更改请求的 url 比请求更快,因此更改请求的 url 是在请求完成之前完成的。我可以做些什么来实现我想要的?
这是代码
let opt = {
transform: function(body) {
return cheerio.load(body);
}
};
router.post('/api', function(req, res) {
let idArray = req.body.data;
for(var i=0; i<idArray.length; i++) {
opt.uri = baseURL + idArray[i];
request(opt)
.then(function($) {
console.log($('video').src);
}
日志(它打印同样的东西)
https://example.mp4/asdfasdf
https://example.mp4/asdfasdf
编辑
当我使用这段代码时,我从 idArray[i]
得到 undefinedfor(var i=0; i<idArray.length; i++) {
console.log("Before", baseURL + idArray[i])
rpap(baseURL + idArray[i])
.then(function($) {
console.log(idArray);
console.log("After", baseURL + idArray[i]);
}
日志
before http://example.com/adsfasdf
before http://example.com/famvvasd
after http://example.com/undefined
after http://example.com/undefined
为什么不将新的 uri 与全局选项对象合并?我建议不要更改全局选项对象,因为可以发出多个请求并且可以以意想不到的方式更改道具。
for (var i = 0; i < idArray.length; i++) {
let uri = baseURL + idArray[i];
request({
...opt,
uri // expands to uri: uri as per es6 style
})
.then(function($) {
console.log($('video').src);
})
}
此外,如果您总是使用转换选项,则可以将其设置为默认值。使用 request-promise 它看起来像这样(来自他们的文档):
var rpap = rp.defaults({ transform: autoParse });
rpap('http://google.com')
.then(function (autoParsedBody) {
// :)
});
rpap('http://echojs.com')
.then(function (autoParsedBody) {
// =)
});