0

成功的请求:

$ 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 ;
4

1 回答 1

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)
    })
})
于 2018-12-24T14:09:38.673 回答