如何使用 Webpack 的 http-proxy-middleware 将_some_ 请求代理到“/”?
How do I proxy _some_ requests to '/' using http-proxy-middleware for Webpack?
我正在尝试解决一个应用程序的独特问题,我需要使用 webpack dev-server 的 proxy
功能将特定请求代理到后端服务。
我遇到的问题是弄清楚如何处理一个奇怪的用例。
我有 Webpack DevServer (WDS) 为我的 index.html
单页应用程序提供多个 client-side 路由。 SPA 向需要代理的不同端点发出客户端 AJAX/fetch 请求。不幸的是,其中一个端点是服务器上的 /
但仅适用于带有特定 Content-Type
header 的请求(我无法更改此服务正在侦听的路径,因此添加一些path-prefix 在这里不是一个选项。
我试过在我的 WDS 配置中使用 bypass
选项来做这样的事情:
proxy: {
"/": {
target: "http://ows.local:6273",
logLevel: "debug",
secure: false,
bypass: (req) => {
console.log(`req.path => `, req.path)
if (req.headers.accept.indexOf('html') !== -1) {
console.log('Skipping proxy for HTML request.')
return 'src/index.html'
}
return null
}
}
}
问题出现在初始调用 HTML 时,WDS 应该提供编译的 .js
和 .css
注入包。我得到的只是基础 src/index.html
w/o 注入的资产(没有注入 <script>
标签)。这是有道理的,因为我知道我在这里告诉代理,"Don't proxy this request to the target, just serve up the contents of this file",但这不是我想要的。我需要编译后的 index.html
WDS 作为默认值,带有注入的资产。
所以这是我的问题,有一些特殊性:
我如何从本质上告诉代理,"For requests that have Content-type: application/json(or whatever)
, go ahead and proxy them through to the target
, but for calls for HTML
, don't proxy then, just serve up the WDS-compiled index.html
"?
原来,解决这个问题只需要调整 bypass()
函数的 return 值。
proxy: {
"/": {
target: proxyTargetUtl,
secure: false,
logLevel: "debug",
bypass: (req) => (req.headers.accept.includes("html") ? "/" : null)
}
我正在尝试解决一个应用程序的独特问题,我需要使用 webpack dev-server 的 proxy
功能将特定请求代理到后端服务。
我遇到的问题是弄清楚如何处理一个奇怪的用例。
我有 Webpack DevServer (WDS) 为我的 index.html
单页应用程序提供多个 client-side 路由。 SPA 向需要代理的不同端点发出客户端 AJAX/fetch 请求。不幸的是,其中一个端点是服务器上的 /
但仅适用于带有特定 Content-Type
header 的请求(我无法更改此服务正在侦听的路径,因此添加一些path-prefix 在这里不是一个选项。
我试过在我的 WDS 配置中使用 bypass
选项来做这样的事情:
proxy: {
"/": {
target: "http://ows.local:6273",
logLevel: "debug",
secure: false,
bypass: (req) => {
console.log(`req.path => `, req.path)
if (req.headers.accept.indexOf('html') !== -1) {
console.log('Skipping proxy for HTML request.')
return 'src/index.html'
}
return null
}
}
}
问题出现在初始调用 HTML 时,WDS 应该提供编译的 .js
和 .css
注入包。我得到的只是基础 src/index.html
w/o 注入的资产(没有注入 <script>
标签)。这是有道理的,因为我知道我在这里告诉代理,"Don't proxy this request to the target, just serve up the contents of this file",但这不是我想要的。我需要编译后的 index.html
WDS 作为默认值,带有注入的资产。
所以这是我的问题,有一些特殊性:
我如何从本质上告诉代理,"For requests that have Content-type: application/json(or whatever)
, go ahead and proxy them through to the target
, but for calls for HTML
, don't proxy then, just serve up the WDS-compiled index.html
"?
原来,解决这个问题只需要调整 bypass()
函数的 return 值。
proxy: {
"/": {
target: proxyTargetUtl,
secure: false,
logLevel: "debug",
bypass: (req) => (req.headers.accept.includes("html") ? "/" : null)
}