Node.js https 失败,而浏览器、`curl` 和 `wget` 成功?
Node.js https fails, whereas browser, `curl` & `wget` succeed?
成功的请求:
$ 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 ;
我假设您正在尝试从您无权访问的远程服务器获取文件。当您使用 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)
})
})
成功的请求:
$ 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 ;
我假设您正在尝试从您无权访问的远程服务器获取文件。当您使用 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)
})
})