首页 > 解决方案 > 不能使用来自 URL 的代理

问题描述

我可以毫无问题地使用代理

var proxies = fs.readFileSync('proxies.txt', 'utf-8').replace(/\r/gi, '').split('\n');

但是当我这样做时

(function scrapeProxies() {
request.get('https://mezy.wtf/proxies.txt', (err, res, body) => {
    proxies = body.split('\n');
    setTimeout(() => scrapeProxies(), 2 * 60 * 1000);
});

无论我做什么,它似乎都不起作用,给出错误

“TypeError:无法读取 null 的属性‘长度’”

如果有人可以帮助我,那就太好了,因为我对此很陌生,只是在学习!将不胜感激,谢谢。

这是我的代码,因为太长了,我无法在此处上传,无法全部粘贴:

https://pastebin.com/raw/HNQYBXyG

标签: javascriptnode.js

解决方案


根据您的代码,以下应该可以工作

const scrapeProxies = () => {
        request.get('https://mezy.wtf/proxies.txt', (err, res, body) => {
            if (err) throw err;

            proxies = body.replace(/\r/gi, '').split('\n');
            setTimeout(() => scrapeProxies(), 2 * 60 * 1000);
        })
    };


scrapeProxies();

您的代码存在以下问题:

1st - 您需要检查完成的请求中是否有任何错误

if (err) throw err;

这意味着如果发现错误,它将抛出异常。

2nd - 在你用 '\n' 分割后,数组中的每个字符串仍然有 '\r',这就是为什么你需要像第一个示例中所做的那样将其替换为空。

 body.replace(/\r/gi, '')

或者你可以直接用 '\r\n' 分割。

 body.split('\r\n');

推荐阅读