How do I deploy NodeJS(backend REST API) and frontend (React) all served by Nginx

Posted April 16, 2020 2.7k views


A brief description of my stack is required, i have nodejs, react on ubuntu 18.04 . I want to use nginx to redirect all API calls to and also serve react on or Am halfway through as i have already nginx redirecting both backend and frontend; however a problem arose i can’t make api calls from the frontend to the backend. as am getting cors Errors. more specifically the resource at has been blocked by cors policy this the nginx conf of

  location / {
        proxy_pass http://localhost:5001;
        proxy_http_version 1.1;
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        set $cors '';
if ($http_origin ~ '^https?://(localhost|www\.cinetie\.com|cinetie\.com)') {
        set $cors 'true';
if ($cors = 'true') {Connection reset by port 22
        more_set_headers 'Access-Control-Allow-Origin' "$http_origin" always;
D:\apps\nodejs\cinetie-backend>s-Control-Allow-Credentials' 'true' always;
        more_set_headers 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
        more_set_headers 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
        # required to be able to read Authorization header in frontend
        more_set_headers -s '400 422 403 404 401 500 522 503'
        more_set_headers 'Access-Control-Expose-Headers' 'Authorization' always;

if ($request_method = 'OPTIONS') {
        # Tell client that this pre-flight info is valid for 20 days
        more_set_headers 'Access-Control-Max-Age' 1728000;
        more_set_headers 'Content-Type' 'text/plain charset=UTF-8';
        more_set_headers 'Content-Length' 0;                                                                                                                                    return 204;                                                                                                                                                     }

So how do i fix this ?

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

2 answers

Have you solved your issue? I also want to know how to.

Yeah you have to :

install cors dependancy : npm install cors
add :
const app = express()
app.use(cors({origin : '*'}))

This little code is attaching cors to all of you routes to accept every domain name allowing to connect with your app
Then redeploy it…

Submit an Answer