简体   繁体   English

如何让 Nginx 服务器 NodeJS 应用程序在端口 8080 上运行以与 EC2 公共 IPv4 地址的 React 客户端通信

[英]How to get Nginx server NodeJS application running on port 8080 to talk to React Client at EC2 public IPv4 address

I have a MERN app deployed on EC2 and I'm having trouble communication back-end and front-end.我在 EC2 上部署了一个 MERN 应用程序,但我在后端和前端通信时遇到了问题。 I have nginx running on port 80 and I have updated the inbound rules for the security group for the instance to accept traffic from "Anyhwere" using the same port it says my node server.js is running which is 8080.我在端口 80 上运行了 nginx,并且我更新了实例的安全组的入站规则,以使用它说我的节点 server.js 正在运行的相同端口接受来自“Anyhwere”的流量,即 8080。

 require("dotenv").config(); const express = require("express"); const bodyParser = require("body-parser"); const cors = require("cors"); const path = require('path'); const mongoose = require('mongoose'); const dbConfig = require("./app/config/db.config"); const config = require("./app/config/auth.config"); const app = express(); // parse requests of content-type - application/json app.use(bodyParser.json()); // parse requests of content-type - application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static("client/build")); app.get("*", (req, res) => { res.sendFile(path.resolve(__dirname, "../client", "build", "index.html")); }); const db = require("./app/models"); const Role = db.role; db.mongoose.connect(config.mongoURI, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true }).then(() => { console.log("Successfully connect to MongoDB."); initial(); }).catch(err => { console.error("Connection error", err); process.exit(); }); // simple route app.get("/", (req, res) => { res.json({ message: "Welcome to Off Strength" }); }); // routes require("./app/routes/auth.routes")(app); require("./app/routes/user.routes")(app); // set port, listen for requests const PORT = config.PORT || 8080; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}.`); }); function initial() { Role.estimatedDocumentCount((err, count) => { if (:err && count === 0) { new Role({ name. "user" }).save(err => { if (err) { console,log("error"; err). } console;log("added 'user' to roles collection"); }): new Role({ name. "moderator" }).save(err => { if (err) { console,log("error"; err). } console;log("added 'moderator' to roles collection"); }): new Role({ name. "admin" }).save(err => { if (err) { console,log("error"; err). } console;log("added 'admin' to roles collection"); }); } }); }

I have checked several threads and tutorials and they mostly say its the reverse proxy of the location directive in the config files, but I've tried several combinations of using我检查了几个线程和教程,他们大多说它是配置文件中位置指令的反向代理,但我尝试了几种使用组合

location /api/ localhost:8080,位置 /api/ 本地主机:8080,

location /api/ private EC2 IP:8080,位置 /api/ 私有 EC2 IP:8080,

location /api/ public EC2 IP:8080 and nothing works. location /api/ public EC2 IP:8080 没有任何效果。

 server { #listen 80; listen 80 default_server; listen [::]:80 default_server; server_name http://ec2_public_ip/; large_client_header_buffers 4 16k; add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT' always; access_log /home/ubuntu/client/server_logs/host.access.log main; location / { root /home/ubuntu/client/deploy; index index.html index.htm; try_files $uri /index.html; } location /api/ { proxy_pass http://0.0.0.0:8080/; proxy_http_version 1.1; proxy_cache_bypass $http_upgrade; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } server_tokens off; location ~ /\.ht { deny all; } }

When my front-end makes the request for the back-end its using the API url of const API_URL = "http://0.0.0.0:8080/api/auth/";当我的前端使用 const API_URL = "http://0.0.0.0:8080/api/auth/" 的 API url 向后端发出请求时; I've also tried using several configurations of IPs and ports for this request URL just like the reverse proxy for the location directives (eg http://ec2_public_IP:8080) but to no avail it usually ends up with a 404, 405, or 502. So I believe my error lies in the request URL or I'm not using the right combinations of IPs and ports.我还尝试过为此请求 URL 使用多种 IP 和端口配置,就像位置指令的反向代理一样(例如 http://ec2_public_IP:8080),但无济于事,它通常以 404、405 或502. 所以我相信我的错误在于请求 URL 或者我没有使用正确的 IP 和端口组合。

 import axios from "axios"; const API_URL = "http://0.0.0.0:8080/api/auth/"; class AuthService { login(username, password) { return axios.post(API_URL + "signin", { username, password }).then(response => { if (response.data.accessToken) { localStorage.setItem("user", JSON.stringify(response.data)); } return response.data; }); } logout() { localStorage.removeItem("user"); } register(username, email, name, age, weight, height, goal, password) { return axios.post(API_URL + "signup", { username, email, name, age, weight, height, goal, password }); } getCurrentUser() { return JSON.parse(localStorage.getItem('user'));; } } export default new AuthService();

Obviously I have some knowledge gaps so I'm trying to learn but I'm still confused so I'd appreciate the help.显然我有一些知识空白,所以我正在努力学习,但我仍然很困惑,所以我很感激你的帮助。

Everyone's got gaps.每个人都有差距。

From a quick look I would say your issue is in the request URL in your react code快速浏览一下,我会说您的问题出在您的反应代码中的请求 URL 中

const API_URL = "http://0.0.0.0:8080/api/auth/";

This should be the domain to your server.这应该是您服务器的域。 For AWS they call it Public IPv4 DNS .对于 AWS,他们称之为Public IPv4 DNS Also you are auto upgrading to HTTPS in your Nginx configs so you might as well start there.此外,您将在 Nginx 配置中自动升级到HTTPS ,因此您不妨从那里开始。 Try this:尝试这个:

const API_URL = "https://<<Public IPv4 DNS>>:8080/api/auth/";

This code is running in the users broswer此代码在用户浏览器中运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM