nginx - 生产中出现 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}`);
;
});
解决方案
这将调用您计算机端口 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。
推荐阅读
- if-statement - Lua - 我需要一个 4 条件 if 语句
- java - Build Gradle 依赖项中的库版本 28 和 26.1 不兼容
- javascript - 无法使用 javascript 解析 json
- node.js - 使用 NodeJS App Engine 的云存储 getImageServingUrl
- android - 响应的第一个索引总是显示每次加载新数据,但没有显示在 recyclerview
- python - Tensorflow 替换张量中接近于零的值
- puppet - 在 Windows 上安装包失败;'安装过程中的致命错误'
- html - 如何防止文本从跨度进入兄弟跨度的内容?
- reactjs - React 检查组件重新渲染的次数
- node.js - 如何使用节点将我的 CSS 和 index.html 文件托管到我的本地服务器中