I have deployed a Full Stack React/Node app on AWS EC2 instance using nginx and facing the CORS policy issue which I have already resolved in my code
Index.js
const express = require('express');
const cors = require('cors');
require('dotenv').config();
const app = express()
const port = process.env.PORT || 5000;
// midleware to use API Endpoints
const corsOptions = {
origin: 'http://13.200.107.25'
}
app.use(express.json());
app.use(cors(corsOptions));
// Serving client react app build
const path = require('path');
const _dirname = path.dirname("");
const buildPath = path.join(_dirname , "../client/build");
app.use(express.static(buildPath));
app.get('/*', (req, res) => {
res.sendFile(
path.join(__dirname, "../client/build/index.html"),
(err) => {
if(err)
{
res.status(500).send(err);
}
}
)
})
//Available Routes
app.use('/api/auth', require('./Routes/authRoute'));
// app.use('/api/notes', require('./Routes/notes'))
app.listen(port, () => {
console.log(`iNotebook listening at http://localhost:${port}`)
})
I used pm2 to start backend server which is also serving the ../client/build of my react app
I have changed /etc/nginx/sites-available/default file for configurations
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
location / {
proxy_pass http://localhost:5000;
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;
}
}
I have restarted pm2 and nginx and test nginx syntax configurations using sudo nginx -t
which is successfull
I have given corsOptions as a paramater in my index.js
// midleware to use API Endpoints
const corsOptions = {
origin: 'http://13.200.107.25'
}
app.use(express.json());
app.use(cors(corsOptions));