我正在尝试将 BrowserSync 配置为在服务器模式下工作,并将我的 API 请求代理到在同一台机器上不同端口上运行的后端,使用 http-proxy-middleware .我使用 Gulp 启动 BrowserSync。
BrowserSync 在端口 8081 上运行。我的后端在 8080 上运行。
这是我创建代理中间件的方式:
var proxyApi = proxy('/api', {target : 'http://localhost:8080/api', logLevel : 'debug'});
下面是我如何从我的 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"
});
输出:
[HPM] Proxy created: /api -> http://localhost:8080/api
一切看起来都不错。
但是当我点击例如http://localhost:8081/api/users
,输出为:
[HPM] GET /api/users/123 -> http://localhost:8080/api
...我的客户端收到 404 错误,因为 /api
本身与后端的任何内容都不匹配。
根据我对文档和示例的理解,目标实际上应该是 http://localhost:8080/api/users/123
为什么路径的其余部分(在本例中为 /users/123
)被遗漏了?
使用以下版本:
"gulp": "3.9.1",
"browser-sync": "2.16.0",
"http-proxy-middleware": "0.17.1",
最佳答案
prependPath
选项默认为 true
。此选项由底层库提供:http-proxy .
prependPath: true/false, Default: true - specify whether you want to prepend the target's path to the proxy path
有两种方法可以解决这个问题:
1.) 将您的 target
从 'http://localhost:8080/api'
更改为 'http://localhost:8080'
var proxyApi = proxy('/api', {target: 'http://localhost:8080', logLevel: 'debug'});
2.) 或者,您可以将选项 prependPath
设置为 false
。
var proxyApi = proxy('/api', {target: 'http://localhost:8080/api', prependPath: false, logLevel: 'debug'});
关于javascript - http-proxy-middleware 不转发完整路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39597330/