NodeJS – 如何通过请求下载文件?

我有一个ExternalServe(在本地运行)当我使用浏览器来请求:

本地主机:2013 / ExternalServer / getfilebyname文件名= getStatus.json

然后浏览器下载getStatus.json到下载文件夹。

在我的NodeJS项目中,我想下载getStatus.json文件,我做了:

download.js

var http = require('http'); var fs = require('fs'); function getFile (){ var file = fs.createWriteStream("./../lib/user.json"); var req = http.get("http://localhost:2013/ExternalServer/getfilebyname?filename=getStatus.json", function(res) { res.pipe(file); }); } getFile(); 

但是当我运行:节点download.js系统返回

 <html><head><title>Apache Tomcat/8.0.0-RC1 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 401 - </h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>This request requires HTTP authentication.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/8.0.0-RC1</h3></body></html> 

如何解决它?

最好的问候

您收到以下错误响应:

这个请求需要HTTPauthentication

build议在头中添加授权信息。 喜欢:

 var options = { host: 'localhost', port: 2013, path: '/ExternalServer/getfilebyname?filename=getStatus.json', headers: { 'Authorization': 'Basic ' + new Buffer(uname + ':' + pword).toString('base64') } }; request = http.get(options, function(res) { res.pipe(file); }); 

在代理的情况下,您可以使用以下标题:

 Proxy-Authorization 

服务器需要一个用户名和密码,或者需要另一个授权机制,才能让你以这种方式访问​​文件。

要在node.js中发出请求时查看如何提供用户名和密码,请查看如何在Node.js中使用http.client(如果有基本授权

我们怎么知道这可能是问题?

系统中两个有趣的string返回:

HTTP Status 401

This request requires HTTP authentication

来自Wikipedia:HTTP状态码列表

401未经授权类似于403 Forbidden,但专门用于需要authentication且失败或尚未提供的情况[2]。 响应必须包含一个WWW-Authenticate标题字段,其中包含适用于所请求资源的挑战。 请参见基本访问authentication和摘要访问authentication。

另一种可能性是服务器可能被设置为发出401而不是403,但并不真正接受任何用户名或密码。