4

node.js と Express を使用して API を構築しました。しかし、特定のルートでいくつかのリクエストを外部サーバーにプロキシし、外部サーバーからリクエストを実行しているクリントに応答を表示できるようにする必要があります。

しかし、クライアントがリクエストとともに送信する基本認証も転送する必要があります。

次のようなリクエストモジュールを使用してみました:

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),

})

しかし、外部サーバー(www.external.com)から「403 Forbidden」が返されるため、基本認証ヘッダーを送信していないようです

リクエストは次のようになります。

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 に対して直接行うため、ノードでプロキシを実行するときに問題が発生します。

4

2 に答える 2

2

モジュールは、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)
})
于 2013-11-02T17:12:21.763 に答える