node-http-proxy如何解析目标URL?

问题描述 投票:1回答:1

我遇到了一个问题,我觉得node-http-proxy正在改变我的目标链接。我在下面举了几个例子。

我使用express作为我的服务器并使用Metaweather API。

问题是我能够从https://www.metaweather.com/api/location/2487956/ https://www.metaweather.com/api/location/2487956/2013/4/30/下面的端点获取数据

但是当我尝试从https://www.metaweather.com/api/location/search/?lattlong=36.96,-122.02调用API时

它失败了状态代码500,我带领我认为node-http-proxy122.02之后添加了一些值,因为它没有用/关闭

server.js

const express = require("express");
const next = require("next");
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

const httpProxy = require("http-proxy");

const proxyOptions = {
  changeOrigin: true
};

const apiProxy = httpProxy.createProxyServer(proxyOptions);

const apiUrl =
  "https://www.metaweather.com/api/location/search/?lattlong=36.96,-122.02";

/*
https://www.metaweather.com/api/location/search/?lattlong=36.96,-122.02 - failed with 500
https://www.metaweather.com/api/location/2487956/ - passed
https://www.metaweather.com/api/location/2487956/2013/4/30/ - passed
*/

app
  .prepare()
  .then(() => {
    const server = express();

    server.use("/api", (req, res) => {
      console.log("Going to call this API " + apiUrl);
      apiProxy.web(req, res, { target: apiUrl });
    });

    server.get("*", (req, res) => {
      return handle(req, res);
    });

    server.listen(3000, err => {
      if (err) throw err;
      console.log("> Ready on http://localhost:3000");
    });
  })
  .catch(ex => {
    console.error(ex.stack);
    process.exit(1);
  });

感谢您查看此问题。

javascript node.js express http-proxy node-http-proxy
1个回答
0
投票

我已经在node-http-proxy中重现了这种情况。

common.js中有一个名为urlJoin的函数,它将req.url附加到目标url的末尾。

我不确定意图是什么,但这是一个开始。

这是我的测试:

const urlJoin = function() {
  //
  // We do not want to mess with the query string. All we want to touch is the path.
  //
var args = Array.prototype.slice.call(arguments),
    lastIndex = args.length - 1,
    last = args[lastIndex],
    lastSegs = last.split('?'),
    retSegs;

args[lastIndex] = lastSegs.shift();

//
// Join all strings, but remove empty strings so we don't get extra slashes from
// joining e.g. ['', 'am']
//
retSegs = [
  args.filter(Boolean).join('/')
      .replace(/\/+/g, '/')
      .replace('http:/', 'http://')
      .replace('https:/', 'https://')
];

// Only join the query string if it exists so we don't have trailing a '?'
// on every request

// Handle case where there could be multiple ? in the URL.
retSegs.push.apply(retSegs, lastSegs);

return retSegs.join('?')
};

let path = urlJoin('/api/location/search/?lattlong=36.96,-122.02', '/');

console.log(path);
//                 /api/location/search/?lattlong=36.96,-122.02/
© www.soinside.com 2019 - 2024. All rights reserved.