Solving CORS problem

Bautista Aramendía Pradal / November 10, 2021 / 1 min read

javascriptapioptimizationnodejs

Read the Have you ever had to deal with CORS issues? section.Have you ever had to deal with CORS issues?#

alt of the image

When building our page, sometimes we get an error related to CORS. Usually, we get something like this: "... blocked by CORS policy". This means that we aren't able to make our request to the server (GET, POST, PUT, DELETE, etc).


Lucky for us, there is a nice and easy way of solving this problem. The only thing we have to do is go to our project's console, and once there, we enter the `npm i cors` command. This will install a package that will deal with our CORS problems.

Then we have to go to the file where we got our server running and write the following lines of code:

Read the const cors = require('cors') section.const cors = require('cors')#

Read the app.use(cors()) section.app.use(cors())#

Read the React.js code section.React.js code#

1const express = require('express');
2const yourServer = require('yourServer')
3const app = express();
4
5const cors = require('cors')
6app.use(cors())
7
8
9