node.js - Node ,使用基本身份验证 header 向外部 API 表达 API 代理请求

标签 node.js api express proxy

我已经使用 node.js 和 express 构建了一个 API。 但是我需要能够将特定路由上的一些请求代理到外部服务器,并显示从外部服务器到执行请求的 clint 的响应。

但我还需要转发客户端随请求一起发送的基本身份验证。

我试过像这样使用请求模块:

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

})

但它似乎没有发送基本的身份验证 header ,因为我从外部服务器 (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 执行完全相同的请求,它会起作用,因此在 Node 中执行代理时会出现一些问题。

最佳答案

request 模块完全不知道您未显式传递给它的任何内容。要设置请求 header 并复制响应 header ,请执行以下操作:

// 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)
})

关于node.js - Node ,使用基本身份验证 header 向外部 API 表达 API 代理请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19743805/

相关文章:

php - 无法对来 self 的服务器 (php) 的某些 url 使用 file_get_contents()

java - 资源定位器上的 Jaxrs 过滤器

node.js - 如何使用 mongo/mongoose 连接远程数据库

node.js - 在 NodeJS/Express/React 堆栈中记录错误

node.js - 如何使用 Node 模块从 Electron 应用程序获取空闲时间?

node.js - NodeJS - Mongoose 比 MongoJS 更快吗?

javascript - Angular 6,请求httpClient(类型错误)

java - 如何将此 api 结果更改为 Jtable 格式?

node.js - 实现express js时,Electron JS出现错误

node.js - Mongoose查询回调返回?