I am working on a MERN website, so i got a vps, installed nginx on it to reverseproxy my API endpoint and configured my Cloudflare DNS records.
So am using a subdomain for frontend , and another one for api like this.
https://api.mywebsite.com for my api endpoint.
https://front.mywebsite.com for my frontend. (mywebsite.com is showing coming soon page , gonna change the front path to the main domain once i complete)
when trying to access frontend i got this error :
Access to XMLHttpRequest at 'https://api.mywebsite.com/apiendpoint' from origin 'https://front.mywebsite.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
The thing is i did add cors module to my app.js file and used it as middleware to allow access from front.mywebsite.com as i did add some configurations to nginx config file.
My app.js code :
//imports Here :
const express = require('express');
//const session = require('express-session');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const mongoStore = require('connect-mongo');
//declare app here :
const app = express();
app.disable('x-powered-by');
app.set('view engine','ejs');
app.set('views','Views');
app.use(express.static(__dirname + '/Public'));
app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({extended:true}));
app.use(cors(
origin:process.env.FRONT_END; // i did try '*' here and i got same error
));
//Clients API Routes :
app.use(process.env.CLIENT_API_PATH,require('./Routes/clientAPIRoutes'));
//Admin Pages Routes :
app.use(process.env.ADMIN_PATH,require('./Routes/adminPageRoutes'));
// app.use('/',(req,res)=>{
// //block main route access
// res.send("Forbidden 403");
// });
module.exports = app;
where process.env.FRONT_END = https://front.mywebsite.com
And this is my nginx configurations :
server{
listen 80;
root /home/user/mywebsite.com/frontend/build;
index index.html index.htm index.nginx-debian.html;
server_name front.mywebsite.com;
try_files $uri /index.html;
location /robots.txt {
alias /home/user/mywebsite.com/frontend/build/robots.txt;
}
}
server {
listen 80;
server_name api.mywebsite.com;
add_header Access-Control-Allow-Origin *;
location / {
proxy_pass "http://localhost:5555" ;
}
}
What am i missing ? should i configure nginx only , express js only , or both of them so i can solve this issue . And could it be because am using cloudflare and how to fix it ?