Fixing a CORS error
Table of contents
Introduction
In this article, I will show how you can solve the CORS
error which is one of the most common errors that occur when trying to integrate a front-end with the server-side.
Problem Statement
Let's say that you're building an application and trying to run a post request or you're trying to access data across another platform but you end up getting an error like this: Access to XMLHttpRequest at https://exampleurl from origin http://localhost:3000 has been blocked by CORS policy. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
.
What is CORS
CORS
is a security feature in all search engines which blocks websites and applications that could be malicious to a user.
Solution
In your server-side code install this package in the terminal:
npm i cors
Then write this code in your main file:
let cors = require("cors");
app.use(cors());
This will initialize the cors
package and stop the error from happening 🥳.