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

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

我在 EC2 上部署了一个 MERN 应用程序,但我在后端和前端通信时遇到问题。我在端口 80 上安装了 nginx 运行,我已经更新了实例安全组的入站规则,以使用它表示我的节点 server.js 是 [=62= 的同一端口接受来自“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");
      });
    }
  });
}

我检查了几个线程和教程,他们大多说它是配置文件中位置指令的反向代理,但我尝试了几种使用组合

位置/api/ localhost:8080,

位置/api/ 私人 EC2 IP:8080,

位置/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;
    }

}


                    

当我的前端使用 API url 向后端发出请求时 const API_URL = "http://0.0.0.0:8080/api/auth/";我也尝试过为此请求使用 IP 和端口的多种配置 URL 就像位置指令的反向代理(例如 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();

显然我有一些知识空白,所以我正在努力学习,但我仍然感到困惑,所以我很感激你的帮助。

每个人都有差距。

快速浏览一下,我会说你的问题出在你的反应代码URL中的请求

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

这应该是您服务器的域。对于 AWS,他们称之为 Public IPv4 DNS。此外,您正在 Nginx 配置中自动升级到 HTTPS,因此您不妨从那里开始。 试试这个:

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

此代码在用户浏览器运行中