我正在尝试使用 request
和 cheerio
从帖子参数的链接中获取每个视频的 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] 得到未定义
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 与全局选项对象合并呢?我建议不要更改全局选项对象,因为可以发出多个请求,并且可以以意想不到的方式更改 Prop 。
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);
})
}
此外,如果您始终使用转换选项,则可以将其设置为默认值。使用请求 promise ,它看起来像这样(来自他们的文档):
var rpap = rp.defaults({ transform: autoParse });
rpap('http://google.com')
.then(function (autoParsedBody) {
// :)
});
rpap('http://echojs.com')
.then(function (autoParsedBody) {
// =)
});
关于javascript - 如何通过每个循环更改请求 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42172651/