Node.js https失败,而浏览器curl和wget成功吗?

时间:2018-12-24 13:35:27

标签: node.js https http-headers http-status-code-403 node-https

成功请求:

$ url='https://svn.tools.ietf.org/svn/tools/xml2rfc/trunk/cli/xml2rfc/data/xml2rfc.css'
$ curl "$url"
$ wget -qO - "$url"
$ python -c 'import webbrowser; webbrowser.open("'"$url"'", new=2)'

失败请求:

$ echo 'require("https").get("'"$url"'", res => console.info("statusCode:", res.statusCode, ";"));' | node

失败请求的输出:

statusCode: 403 ;

1 个答案:

答案 0 :(得分:1)

我假设您正在尝试从您无权访问的远程服务器上获取文件。使用nodejs https程序包调用远程服务器时,必须设置用户代理。尝试以下代码:

let https = require('https')
let pageUrl = 'https://svn.tools.ietf.org/svn/tools/xml2rfc/trunk/cli/xml2rfc/data/xml2rfc.css'
let url = require('url')

let options = url.parse(pageUrl)
options.headers = {
    'User-Agent': 'request'
};
let req = https.get(options, (res) => {
    console.log("statusCode: ", res.statusCode);
    console.log("headers: ", res.headers);
    let data = ""
    res.on('data', (chunk) => {
        data += chunk
    })

    res.on('end', (chunk) => {
        console.log("ended")
        console.log(data)
    })
})