Issue
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
href="https://i.stack.imgur.com/unsvH.png" rel="nofollow noreferrer">
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));
Solution
I think your cors configurations are ok.
A good way to realize if your Headers are ok is using curl in a bash terminal.
curl http://13.200.107.25 -I
This command shows you the headers of your website:
HTTP/1.1 200 OK
Server: nginx/1.18.0 (Ubuntu)
Date: Tue, 01 Aug 2023 15:56:25 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 1457
Connection: keep-alive
X-Powered-By: Express
Access-Control-Allow-Origin: http://13.200.107.25 #<---- CORS
Vary: Origin
Accept-Ranges: bytes
Cache-Control: public, max-age=0
Last-Modified: Tue, 01 Aug 2023 14:11:19 GMT
ETag: W/"5b1-189b1705fac"
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.
Answered By - clay Answer Checked By - David Goodson (WPSolving Volunteer)