Fixing a CORS error

Noor AhmedNoor Ahmed
1 min read

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 🥳.

0
Subscribe to my newsletter

Read articles from Noor Ahmed directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Noor Ahmed
Noor Ahmed

I am a software engineer intern from the UK and I have worked with multiple technologies like MERN stack, JavaScript, Python etc. I also like to contribute to open source on Github.