Skip to content

Commit 14337e3

Browse files
WebpackDevMiddleware now preserves client's view of hostname when doing 302 to /__webpack_hmr
1 parent 698921d commit 14337e3

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

src/Microsoft.AspNetCore.SpaServices/Webpack/WebpackDevMiddleware.cs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ namespace Microsoft.AspNetCore.Builder
1515
public static class WebpackDevMiddleware
1616
{
1717
private const string WebpackDevMiddlewareScheme = "http";
18-
private const string WebpackDevMiddlewareHostname = "localhost";
1918
private const string WebpackHotMiddlewareEndpoint = "/__webpack_hmr";
2019
private const string DefaultConfigFile = "webpack.config.js";
2120

@@ -64,19 +63,27 @@ public static void UseWebpackDevMiddleware(
6463
JsonConvert.SerializeObject(devServerOptions)).Result;
6564

6665
// Proxy the corresponding requests through ASP.NET and into the Node listener
66+
// Note that this is hardcoded to make requests to "localhost" regardless of the hostname of the
67+
// server as far as the client is concerned. This is because ConditionalProxyMiddlewareOptions is
68+
// the one making the internal HTTP requests, and it's going to be to some port on this machine
69+
// because aspnet-webpack hosts the dev server there. We can't use the hostname that the client
70+
// sees, because that could be anything (e.g., some upstream load balancer) and we might not be
71+
// able to make outbound requests to it from here.
6772
var proxyOptions = new ConditionalProxyMiddlewareOptions(WebpackDevMiddlewareScheme,
68-
WebpackDevMiddlewareHostname, devServerInfo.Port.ToString());
73+
"localhost", devServerInfo.Port.ToString());
6974
appBuilder.UseMiddleware<ConditionalProxyMiddleware>(devServerInfo.PublicPath, proxyOptions);
7075

7176
// While it would be nice to proxy the /__webpack_hmr requests too, these return an EventStream,
7277
// and the Microsoft.AspNetCore.Proxy code doesn't handle that entirely - it throws an exception after
73-
// a while. So, just serve a 302 for those.
78+
// a while. So, just serve a 302 for those. But note that we must use the hostname that the client
79+
// sees, not "localhost", so that it works even when you're not running on localhost (e.g., Docker).
7480
appBuilder.Map(WebpackHotMiddlewareEndpoint, builder =>
7581
{
7682
builder.Use(next => async ctx =>
7783
{
84+
var hostname = ctx.Request.Host.Host;
7885
ctx.Response.Redirect(
79-
$"{WebpackDevMiddlewareScheme}://{WebpackDevMiddlewareHostname}:{devServerInfo.Port.ToString()}{WebpackHotMiddlewareEndpoint}");
86+
$"{WebpackDevMiddlewareScheme}://{hostname}:{devServerInfo.Port.ToString()}{WebpackHotMiddlewareEndpoint}");
8087
await Task.Yield();
8188
});
8289
});

0 commit comments

Comments
 (0)