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));
2
Answers
I think your cors configurations are ok.
A good way to realize if your Headers are ok is using curl in a bash terminal.
This command shows you the headers of your website:
As you can see the cors header is ok.
The problem is that your front is attempting to connect to http://localhost:5000 and this is confusing because you said that your backend (node) is in the same EC2 (not in localhost).
If your backend is running in the same EC2 instance the solution is changing every http://localhost:5000 request in your react project for http://13.200.107.25. In this case, the CORS header is not necessary because the requests are from the same origin.
If actually, your backend is running on your personal computer (localhost) you must configure cors(in your backend) with http://localhost… and depending on your browser configure it to allow make this request like in this question CORS error on request to localhost dev server from remote site . Because fetching localhost from websites already hosted on the internet is not secure.
Assuming 13.200.107.25 is your ubuntu server the backend NojeJs + Express should be:
Nginx should be:
http://13.200.107.25/api will access your backend API.