Report this

What is the reason for this report?

How to Disable CORS for NodeJS Nginx Ubuntu 20.04 Server

Posted on June 6, 2022

Hello I am using Nginx with NodeJS on Ubuntu 20.04 to set up a reverse proxy server to host a NodeJS Typescript API using PM2.

I have enabled CORS in the Nginx default file as well as in the TS file headers. However when I try to make a http request to the API in my Angular front-end I still get CORS error.

The API is hosting fine and can be accessed in the web browser to get a simple response.



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

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.

Hi there,

To disable CORS for your Node.js API, you will need to configure Nginx to add the necessary CORS headers to the response from your API.

Here is an example of how you might do this in your Nginx configuration:

location /api {
    proxy_pass http://localhost:3000;
    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;
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
}

This configuration tells Nginx to pass requests to the /api path to the Node.js API running on port 3000, and to add the necessary CORS headers to the response. The add_header directives specify the values for the Access-Control-Allow-Origin, Access-Control-Allow-Credentials, Access-Control-Allow-Methods, and Access-Control-Allow-Headers headers, respectively.

Keep in mind that you may also need to configure CORS in your Node.js API itself, depending on how it is implemented. For example, if you are using the cors library, you can use the cors() middleware to enable CORS for your API.

Best,

Bobby

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Start building today

From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.