首页 > 解决方案 > 生产中出现 net::ERR_CONNECTION_REFUSED 错误

问题描述

我已经部署了我的反应应用程序,它也有一个后端。我已经使用 npm start 命令从我的服务器启动了我的前端和后端。前端工作正常,但后端不正常。(从本地主机完美运行)

前端从 3000 端口打开,后端从 9000 端口打开。

这是我的 nginx 配置

    server {
       server_name myservername.com www.myservername.com;
       location / {
         proxy_pass http://localhost:3000;
         proxy_http_version 1.1;
         proxy_set_header Upgrade $http_upgrade;
         proxy_set_header Connection "upgrade";  
       }
    }

server {
   if($host = www.myservername.com){
     return 301 https://$host$request_uri;
   }
   if($host = myservername.com){
     return 301 https://$host$request_uri;
   }
   listen 80 default_server;
   listen [::]:80 default_server;

   server_name myservername.com www.myservername.com;

   return 404;

}

正在使用的端口

在此处输入图像描述

我在控制台中遇到的错误

POST http://localhost:9000/bot net::ERR_CONNECTION_REFUSED

我该如何解决这个问题?

问题是尝试执行此获取

fetch("http://localhost:9000/bot", {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
      }).then(res => res.text())
        .then(res => {
          res = JSON.parse(res);
          this.setState({ apiResponse: res.response, apiIntent: res.intent}, () => {this.setBotMsg()}); 
          console.log(`This is the response: ${res.response}, ${res.intent}`); 
          ;
        });

标签: nginxserverlocalhostconnection-refused

解决方案


这将调用您计算机端口 9000 上的本地环回适配器。我认为这不是您想要的。使用您的服务器 IP 或域名代替 localhost。

fetch("http://myservername.com:9000/bot", {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
      }).then(res => res.text())
        .then(res => {
          res = JSON.parse(res);
          this.setState({ apiResponse: res.response, apiIntent: res.intent}, () => {this.setBotMsg()}); 
          console.log(`This is the response: ${res.response}, ${res.intent}`); 
          ;
        });

我会使用 NGINX 将请求代理到您的后端,而不是直接公开端口 9000。

fetch("https://myservername.com/bot", {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
      }).then(res => res.text())
        .then(res => {
          res = JSON.parse(res);
          this.setState({ apiResponse: res.response, apiIntent: res.intent}, () => {this.setBotMsg()}); 
          console.log(`This is the response: ${res.response}, ${res.intent}`); 
          ;
        });

nginx 配置取决于您想要做什么。子域或位置?子域可能类似于bot.myserver.com. 一个位置myserver.com/bot

server {
 listen 443


  .....


  location /bot {
    proxy_pass http://localhost:9000;
    proxy_set_header Host $host;
    ....
  }

}

附加说明:我已更新配置以从前端使用 https。


推荐阅读