如何使用热重载正确配置 nginx 与 Angular 一起使用?

sko*_*000 3 nginx angular13 angular14

我使用命令运行我的服务器应用程序:ng serve并在浏览器控制台中收到错误:

Firefox 无法连接到 wss://dev.domain.com/ws 服务器。

[webpack-dev-server] 正在尝试重新连接...

或者在镀铬物上:

与“wss://dev.domain.com/ws”的 WebSocket 连接失败

[webpack-dev-server] 已断开连接!

[webpack-dev-server] 正在尝试重新连接...

我的 nginx 配置是:

location ^~ / {
    proxy_pass         http://localhost:4200;
    proxy_set_header   X-Forwarded-For $remote_addr;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
   
    proxy_http_version 1.1;
    proxy_cache_bypass $http_upgrade;
}

location ^~ /sockjs-node/ {

    proxy_pass http://localhost:4200;

    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;

    proxy_http_version 1.1;
    proxy_cache_bypass $http_upgrade;
}

location ^~ /ws/ {

    proxy_pass http://localhost:4200;

    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;

    proxy_http_version 1.1;
    proxy_cache_bypass $http_upgrade;
}
Run Code Online (Sandbox Code Playgroud)

这应该有效,但事实并非如此。我的配置有误吗?

Vla*_*lad 6

这对我的 Angular 14 有用:

 location /ng-cli-ws {
           proxy_pass http://host-gateway:4200;
           proxy_http_version 1.1;
           proxy_set_header Upgrade $http_upgrade;
           proxy_set_header Connection "Upgrade";
           proxy_set_header Host $host;
 }
Run Code Online (Sandbox Code Playgroud)

如果您的应用程序使用 /ws,请尝试删除结尾斜杠,否则 nginx 会向 /ws/... 响应 301