Home > OS >  How to get Nginx server NodeJS application running on port 8080 to talk to React Client at EC2 publi
How to get Nginx server NodeJS application running on port 8080 to talk to React Client at EC2 publi

Time:12-16

I have a MERN app deployed on EC2 and I'm having trouble communication back-end and front-end. 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.

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,

location /api/ private EC2 IP:8080,

location /api/ public EC2 IP:8080 and nothing works.

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/"; I've also tried using several configurations of IPs and ports for this request URL just like the reverse proxy for the location directives (e.g. 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.

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.

CodePudding user response:

Everyone's got gaps.

From a quick look I would say your issue is in the request URL in your react code

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. Also you are auto upgrading to HTTPS in your Nginx configs so you might as well start there. Try this:

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

This code is running in the users broswer

  • Related