简体   繁体   English

http-proxy-middleware不会转发完整路径

[英]http-proxy-middleware does not forward the full path

I am trying to configure BrowserSync to work in server mode and to proxy my API requests to the backend that runs on the same machine on a different port, using http-proxy-middleware . 我正在尝试将BrowserSync配置为在服务器模式下工作,并使用http-proxy-middleware将我的API请求代理到在不同端口上的同一台机器上运行的后端。 I use Gulp to launch BrowserSync. 我使用Gulp启动BrowserSync。

BrowserSync runs on port 8081. My backend runs on 8080. BrowserSync在端口8081上运行。我的后端运行在8080上。

Here is how I create the proxy middleware : 以下是我创建代理中间件的方法:

var proxyApi = proxy('/api', {target : 'http://localhost:8080/api', logLevel : 'debug'});

And here is how I run BrowserSync from my Gulp task : 以下是我从Gulp任务中运行BrowserSync的方法:

// Init BrowserSync with proxies as middleware and based on the dest dir
browserSync.init({
    open: true,
    port: config.proxyPort,
    server: {
        baseDir: config.destDir,
        middleware: [proxyApi]
    },
    browser: "google chrome"
});

The output : 输出 :

[HPM] Proxy created: /api  ->  http://localhost:8080/api

Everything looks good. 一切都很好看。

But When I hit eg http://localhost:8081/api/users , the output is : 但当我点击例如http://localhost:8081/api/users ,输出为:

[HPM] GET /api/users/123 -> http://localhost:8080/api

...And my client gets a 404 error because /api on its own does not match anything on the backend. ...而我的客户端收到404错误,因为/api本身与后端的任何内容都不匹配。

From what I understood from the doc and examples, the target should actually be http://localhost:8080/api/users/123 根据我从doc和examples中的理解,目标应该实际上是http://localhost:8080/api/users/123

Why is the rest of the path (in this case /users/123 ) being left out ? 为什么路径的其余部分(在这种情况下为/users/123 )被遗漏了?

Using the following versions : 使用以下版本:

"gulp": "3.9.1",
"browser-sync": "2.16.0",
"http-proxy-middleware": "0.17.1",

The prependPath option is true by default. 默认情况下, prependPath选项为true This option is provided by the underlying lib: http-proxy . 此选项由基础lib提供: http-proxy

prependPath : true/false, Default: true - specify whether you want to prepend the target's path to the proxy path prependPath :true / false,默认值: true - 指定是否要将目标的路径添加到代理路径

There are two ways to fix the issue: 有两种方法可以解决此问题:

1.) Change your target from 'http://localhost:8080/api' to 'http://localhost:8080' 1.)将target'http://localhost:8080/api'更改为'http://localhost:8080'

var proxyApi = proxy('/api', {target: 'http://localhost:8080', logLevel: 'debug'});

2.) Alternatively you can set the option prependPath to false . 2.)或者,您可以将选项prependPath设置为false

var proxyApi = proxy('/api', {target: 'http://localhost:8080/api', prependPath: false, logLevel: 'debug'});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM