在使用Nginx的Next.js中,连接到'ws://localhost/_next/webpack-hmr'的WebSocket连接失败:WebSocket在连接建立之前已关闭。

4

我使用 NextJS 和 Socket.IO 开发 Web 应用。

当我运行应用时,一切都正常。但是过了 2 分钟后就会出现错误。

NGINX 日志:

172.19.0.1 - - [12/Sep/2022:16:27:39 +0000] "POST /api/ HTTP/1.1" 200 147 "http://localhost/en" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6.1 Safari/605.1.15"
172.19.0.1 - - [12/Sep/2022:16:27:59 +0000] "GET /_next/webpack-hmr HTTP/1.1" 101 269 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6.1 Safari/605.1.15"
...
172.19.0.1 - - [12/Sep/2022:16:29:21 +0000] "GET /_next/webpack-hmr HTTP/1.1" 101 71 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6.1 Safari/605.1.15"
172.19.0.1 - - [12/Sep/2022:16:29:26 +0000] "GET /_next/webpack-hmr HTTP/1.1" 499 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6.1 Safari/605.1.15"

101--正常。499--错误。但什么也没有发生,错误是从哪里来的?

在控制台上,我看到每个499都会出现这个错误:

WebSocket connection to 'ws://localhost/_next/webpack-hmr' failed: WebSocket is closed before the connection is established

这个问题只在Safari(MacOS)上出现!

在Chrome上一切正常。

1个回答

8
从Next.js 12开始,开发环境中的HMR(热模块替换)使用WebSocket连接。
当使用Nginx与Next.js一起时,您需要正确配置它以适应WebSocket请求。

In some cases when proxying requests to the Next.js dev server, you will need to ensure the upgrade request is handled correctly. For example, in nginx you would need to add the following configuration:

location /_next/webpack-hmr {
    proxy_pass http://localhost:3000/_next/webpack-hmr;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade"; 
} 

Next.js, Upgrade Guide, Next.js' HMR connection now uses a WebSocket


谢谢,它有效果了。不过,我只是在现有的规则上添加了额外的标头,而没有创建新的规则。这样做与其他方式相比有什么优势吗? - undefined
@jasxir 在现有规则的基础上进行补充是完全可以的。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接