节点 http-proxy-middleware 无法将本地服务器用作目标

问题描述 投票:0回答:2

我有一个节点服务器,我使用

http-proxy-middleware
代理我的 api 请求,类似于 这篇文章 中发生的情况。当我代理到真实的生产服务器时,一切工作正常,但是当我将代理指向本地服务器时,它就不起作用。

这是我的代码:

app.use('/_api', proxy({target: 'http://localhost:9000', changeOrigin: true}));

服务器开启:

http://localhost:9000/hello
正在工作(我可以从浏览器访问它),但是,当我尝试从我自己的服务器访问它时,如下所示:

http://localhost:3000/_api/hello

我得到:

无法获取/_api/hello

如果我将 localhost:9000 替换为真实服务器,一切正常...

javascript node.js proxy http-proxy node-http-proxy
2个回答
25
投票

您的代理请求正在尝试使用原始请求路径访问本地服务器。

例如,当您提出要求时

http://localhost:3000/_api/hello

您的代理正在尝试访问

http://localhost:9000/_api/hello

您的

_api/hello
上不存在
localhost:9000
路径,这由
Cannot GET /_api/hello
错误所示。

您需要重写代理请求路径以删除

_api
部分:

app.use('/_api', proxy({
    target: 'http://localhost:9000', 
    changeOrigin: true,
    pathRewrite: {
        '^/_api' : '/'
    }
}));

0
投票

修改以下代码即可运行

app.use('/_api', proxy({
  target: 'http://localhost:9000',
  changeOrigin: true,
  pathRewrite: function(path, req) {
    return '/_api'.concat(path)
  }
}));

© www.soinside.com 2019 - 2024. All rights reserved.