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!
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
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.