解决Nginx传递Node程序实时回应无法显示的问题

问题状况

网站是由Nginx转到后端node进行展示处理的,Node端是一个利用ChatGPT的网页对话程序,使用API调用其接口使用。

但页面返回的实时回应无法显示,会在响应完成后再一起显示出来;而使用apache进行转发则没有这个问题。

相关配置

两者均使用websocket方式连接Node处理;Apache相关配置:

<VirtualHost *:443>
    ServerName gpt.xxx.com
    ProxyPass "/" "ws://127.0.0.1:5000/" timeout=30
    ProxyPassReverse "/" "ws://127.0.0.1:5000/" timeout=30
    ErrorLog "| /usr/local/apache/bin/rotatelogs logs/gpt-error-%Y_%m_%d.log 2M"
    ErrorLog "| /usr/local/apache/bin/rotatelogs logs/gpt-error-%Y_%m_%d.log 86400 480"
    CustomLog "| /usr/local/apache/bin/rotatelogs logs/gpt-access-%Y_%m_%d.log 2M" common
    CustomLog "| /usr/local/apache/bin/rotatelogs logs/gpt-access-%Y_%m_%d.log 86400 480" common
    SSLEngine on
    SSLCertificateFile "/etc/letsencrypt/live/xxx.com/cert.pem"
    SSLCertificateKeyFile "/etc/letsencrypt/live/xxx.com/privkey.pem"
    SSLCertificateChainFile "/etc/letsencrypt/live/xxx.com/fullchain.pem"
    BrowserMatch "MSIE [2-5]" \
         nokeepalive ssl-unclean-shutdown \
         downgrade-1.0 force-response-1.0
    <FilesMatch "\.(cgi|shtml|phtml|php)$">
        SSLOptions +StdEnvVars
    </FilesMatch>
</VirtualHost>

Nginx相关配置:

# Nginx second config file for gpt.
# backend
upstream gpt {
    server 127.0.0.1:5000;
}

server {
        listen 80;
        listen 443 ssl;
        server_name gptus.xxx.com;
        ssl_certificate certs/xxx.com.crt;
        ssl_certificate_key certs/xxx.com.key;
        access_log logs/gpt_access.log;
        error_log  logs/gpt_error.log;
    location / {
        proxy_pass http://gpt;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

配置正常,页面均可访问且提问对话;就是Nginx会出现上述状况。

经过排查,使用Nginx的,在提问后,接口通信HTTP的Response Header并未立刻给出响应,而是在服务端完成回答后会一起响应和给出答案:

这样展示就很不友好,正常情况是会显示出回答过程的。

经过测试和验证,这是由于Nginx和Node之间的缓冲区导致,在配置中加入

proxy_buffering off;

禁用Nginx的缓冲,使得响应能够实时显示。

发表评论

error: Content is protected !!