使用基本身份validation标头向外部API表示API代理请求

我已经build立了一个API使用node.js和expression。 但我需要能够代理一些特定的路由到外部服务器的请求,并显示从外部服务器响应请求的clint。

但是我也需要转发客户端发送的基本身份validation请求。

我曾尝试使用请求模块,如:

app.get('/c/users/', function(req,res) { //modify the url in any way you want var newurl = 'https://www.external.com' request(newurl).pipe(res), }) 

但似乎不发送基本的身份validation标题,因为我得到“403禁止”从外部服务器(www.external.com)

请求正在做,看起来像:

 GET http://example.se:4000/c/users/ HTTP/1.1 Accept-Encoding: gzip,deflate X-version: 1 Authorization: Basic bmR4ZHpzNWZweWFpdjdxfG1vcmV1c2*******= Accept: application/json Host: example.se:4000 Connection: Keep-Alive User-Agent: Apache-HttpClient/4.1.1 (java 1.5) 

如果我做的是完全相同的请求,但直接对www.external.com,所以有一些问题,当在代理节点。

request模块完全不知道任何你不明确传递给它的东西。 要设置请求标题并复制响应标题,请执行以下操作:

 // copy headers, except host header var headers = {} for (var key in req.headers) { if (req.headers.hasOwnProperty(key)) { headers[key] = req.get(key) } } headers['host'] = 'final-host' var newurl = 'http://final-host/...' request.get({url:newurl, headers: headers }, function (error, response, body) { // debug response headers console.log(response.headers) // debug response body console.log(body) // copy response headers for (var key in response.headers) { if (response.headers.hasOwnProperty(key)) { res.setHeader(key, response.headers[key]) } } res.send(response.statusCode, body) }) 

尝试像这样显式地传递auth的细节

 request(newurl).auth(username, password).pipe(res); 

https://github.com/mikeal/request#http-authentication