arrays - 在将 URL 记录到数组中的控制台之前检查 URL 是否存在

标签 arrays json node.js request

我正在编写一个用于生成站点地图的 Node 应用程序,但在某个特定部分遇到了问题,我需要 (i) 循环遍历包含许多具有特定 URL 键的产品的 JSON 页面,并检查每个产品的 URL 是否存在,以及 (ii) 如果 URL 确实存在,则需要将此 URL 打印到控制台。

var request = require("request");

var url = "http://linktoJSON"

//reads the JSON from the provided URL
request({
url: url,
json: true
}, function (error, response, body) {

    //loops through each product on the page
    for (i = 0; i < body.length; i++) { 
        //checks if the URL exists for each product
        request('http://www.example.com/product/' + (body[i].urlKey), function (err, response) {
            //if the product page does exist
            if (response.statusCode === 200) {
                    //print the product URL
                    console.log (('<xtml:link\nrel="alternate"\nhreflang="x-default"\nhref="http://www.example.com/' + body[i].urlKey) +'"\n/>');
                    }
            //if the product doesn't exist it does nothing
            else
                {}
    })}

});

这工作得很好,直到它应该打印产品 URL,此时它无法将 [i] 识别为数字,并给我一个错误。是否有其他方法可以将 [i] 的值传递给 console.log 或让它打印与请求所使用的完全相同的链接?

最佳答案

尝试:

var request = require("request");

var url = "http://linktoJSON"

//reads the JSON from the provided URL
request({
    url: url,
    json: true
}, function (error, response, body) {
    //loops through each product on the page
    for (i = 0; i < body.length; i++) { 
        //checks if the URL exists for each product
        processKey(body[i].urlKey);
    } 
});

function processKey(key) {
    request('http://www.example.com/product/' + key, function (err, response) {
        //if the product page does exist
        if (response.statusCode === 200) {
            //print the product URL
            console.log('<xtml:link\nrel="alternate"\nhreflang="x-default"\nhref="http://www.example.com/' + key +'"\n/>');
        }
        //if the product doesn't exist it does nothing
        else
        {
        }
    });
}

并查看此问题以获取信息: JavaScript closure inside loops – simple practical example

关于arrays - 在将 URL 记录到数组中的控制台之前检查 URL 是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27984375/

相关文章:

node.js - Express网关给出404

node.js everyauth twitter mongodb 错误 : You are trying to access the attribute/method configured by `findUserById` , 您没有配置哪个?

arrays - 在 MATLAB 中将整数转换为逻辑数组

python - CSV 到 JSON,从列创建数组

python - 在 NumPy 中使用两个 bool 数组进行索引

json - 在 swift 中创建一个 url 对象

java - 使用 jackson 映射时如何适本地覆盖 equals(Object o)

c - 使用c程序以交叉方式打印字符串

javascript - 将表单 json 响应放在 div block 中(不是 iframe)

node.js - Sequelize 迁移中的关联