Как правильно настроить серверную часть для частных ресурсов для приложения MERN с помощью NGINX/AWS

#node.js #nginx #amazon-ec2 #mern #http-status-code-405

#node.js #nginx #amazon-ec2 #мерн #http-статус-код-405

Вопрос:

Я хочу знать, как следует настроить nginx, зная, что у меня есть приложение MERN, настроенное на AWS EC2, и моя база данных работает на MongoDB Atlas. Я теряюсь в том, как задняя и передняя части взаимодействуют с nginx.

В частности, где я должен вставлять свои адреса IPv4 и IPv6 и как я должен настраивать блоки определения местоположения для доступа к своим API, потому что прямо сейчас я получаю либо 404, либо 405. Я попытался установить значение error_page 405 на 200, но это не сработает в моей ситуации, поскольку пользователям необходимо пройти проверку подлинности для доступа к определенным ресурсам. Все работало и было доступно на локальном хостинге.

Мои API структурированы как /api/аутентификация/регистрация (регистрация, сброс, забытый пропуск) Прямо сейчас мой сервер работает на порту 8080. Для клиента react они настроены как http://ec2-IPv4-address/login (регистрация, сброс, забыл)

server.js

 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();  var corsOptions = {  origin: "http://localhost:8081" };  app.use(cors(corsOptions));  // parse requests of content-type - application/json app.use(bodyParser.json());  app.use(express.static("client/build"));  // parse requests of content-type - application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: true }));  const db = require("./app/models"); const Role = db.role;  db.mongoose  .connect(config.mongoURI  , {  useNewUrlParser: true,  useCreateIndex: true,  useUnifiedTopology: true  })  .then(() =gt; {  console.log("Successfully connect to MongoDB.");  initial();  })  .catch(err =gt; {  console.error("Connection error", err);  process.exit();  });  // simple route app.get("/", (req, res) =gt; {  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, () =gt; {  console.log(`Server is running on port ${PORT}.`); });  function initial() {  Role.estimatedDocumentCount((err, count) =gt; {  if (!err amp;amp; count === 0) {  new Role({  name: "user"  }).save(err =gt; {  if (err) {  console.log("error", err);  }   console.log("added 'user' to roles collection");  });   new Role({  name: "moderator"  }).save(err =gt; {  if (err) {  console.log("error", err);  }   console.log("added 'moderator' to roles collection");  });   new Role({  name: "admin"  }).save(err =gt; {  if (err) {  console.log("error", err);  }   console.log("added 'admin' to roles collection");  });  }  }); } 

Мой файл NGINX по умолчанию.conf

 server { #listen 80;  listen 80 default_server;  listen [::]:80 default_server;  server_name _;   add_header 'Access-Control-Allow-Origin' '*';  add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' 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;  add_header X-Frame-Options SAMEORIGIN;  add_header X-Content-Type-Options nosniff;  add_header X-XSS-Protection "1; mode=block";  add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;";  }    }   location /api/ {  proxy_pass http://127.0.0.1:27017;  proxy_http_version 1.1;  proxy_set_header Upgrade $http_upgrade;  proxy_set_header Connection 'upgrade';  proxy_set_header Host $host;  proxy_cache_bypass $http_upgrade; }   error_page 500 502 503 504 /50x.html;  location = /50x.html {  root /home/ubuntu/server;  }   server_tokens off;   location ~ /.ht {  deny all;  }  } 

Комментарии:

1. Ваш вопрос слишком широк — задавайте более конкретные вопросы. Существует множество руководств по настройке каждого компонента вашего стека MERN. Несколько указателей proxy_pass http://127.0.0.1:27017; — nginx пытается связаться с узлом на локальном хосте 27017 вместо 8081. Ошибки HTTP 405 могут быть связаны с Access-Control-Allow-Methods тем, что вы не включили все глаголы, которые пытаются использовать ваши приложения (PUT и т. Д.)?

2. Спасибо за это. Это помогло направить меня в правильном направлении. Я задам более конкретный вопрос.