CORS Error in React.js

Musab Abbasi
6 min readNov 26, 2021

--

What is CORS?

Cross-Origin Resource Sharing (CORS) is a standard that allows a server to relax the same-origin policy. This is used to explicitly allow some cross-origin requests while rejecting others. For example, if a site offers an embeddable service, it may be necessary to relax certain restrictions. Setting up such a CORS configuration isn’t necessarily easy and may present some challenges. In these pages, we’ll look into some common CORS error messages and how to resolve them.

When do we get a CORS error?

If the CORS configuration isn't setup correctly, the browser console will present an error like "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at $somesite" indicating that the request was blocked due to violating the CORS security rules. This might not necessarily be a set-up mistake, though. It's possible that the request is in fact intentionally being disallowed by the user's web application and remote external service. However, If the endpoint is meant to be available, some debugging is needed to succeed.

Identifying the issue

To understand the underlying issue with the CORS configuration, you need to find out which request is at fault and why. These steps may help you do so:

  1. Navigate to the web site or web app in question and open the Developer Tools.
  2. Now try to reproduce the failing transaction and check the console if you are seeing a CORS violation error message. It will probably look like this:

The text of the error message will be something similar to the following:

Cross-Origin Request Blocked: The Same Origin Policy disallows
reading the remote resource at https://some-url-here. (Reason:
additional information here).

CORS Error in React.js

Often people experience CORS error in React.js when posting data to backend.

To replicate this issue I will create a react.js and Node.js app and will show that how can we solve this issue.

Getting Started

First I will create a React.js App by executing the below command in terminal

npx create-react-app frontend

It will take some time to create react app, till then we will create our express app for backend by executing the list of command below in terminal.

mkdir backend
cd ./backend
npm init -y
npm install express body-parser nodemon

You might have noticed that while creating our React.js app I have named it as frontend and while creating backend I have created a folder as backend with “mkdir backend”. This is because I want to differentiate between our frontend and backend.

Next I have installed two packages in our backend called as express and body-parser.

Now add this line in you backend filer ‘package.json’ file script object.

"start": "nodemon server.js",

Next create a file called as server.js in our backend folder and paste the code below in that file.

const bodyParser = require("body-parser");const express = require("express");const app = express();app.use(bodyParser.json())app.get("/", (req, res)=>{res.send("'/' this is get request");})app.listen(5000, (req, res)=>{console.log("Server is listening on PORT 5000");});

Now run your backend app by executing the below command.

npm start

You will see something like this in your terminal.

Now got this URL (http://localhost:5000/)and you will see something like this.

Now since our backend is working as it should be lets create our frontend in React.js.

We will be creating a folder called components in our frontend src folder.

We will be creating all the components in our components folder. For now we only have to solve post request so we don’t need to create any component we will be using App.js.

Now in your terminal navigate to frontend and execute the below command.

npm install axios

What is Axios

Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs with the same codebase). On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests.

Features of Axios

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

Now run our frontend by executing the below command.

npm start

Now once our frontend is running you will see something like this.

Create a Post request in React.js

import axios from "axios";function App() {function click(){axios.post('http://localhost:5000/post', {firstName: 'Fred',lastName: 'Flintstone'}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});}return (<div className=""><button onClick={click}>Send Request</button></div>);}export default App;

We have created a button on its click we are post data to backend.

Now your frontend will look like this. But there is a problem when you are clicking this button i.e. CORS ERROR.

Now to solve this issue we will be switching back to our backend. We will add a post request in our backend server.js.

const bodyParser = require("body-parser");const express = require("express");const app = express();app.use(bodyParser.json())app.get("/", (req, res)=>{res.send("'/' this is get request");})app.post("/post" ,(req, res)=>{res.send("Request Received!");})app.listen(5000, (req, res)=>{console.log("Server is listening on PORT 5000");});

Handling CORS error in Backend

We will be installing a npm package called as cors. To install this command we will execute the below command.

npm install cors

Now I will be initializing cors in our server.js file and allowing our frontend route to post data.

const bodyParser = require("body-parser");const express = require("express");const app = express();const cors = require("cors");app.use(bodyParser.json());app.use(cors({credentials:true,origin: ['http://localhost:3000']}));app.get("/", (req, res)=>{res.send("'/' this is get request");})app.post("/post" ,(req, res)=>{res.send("Request Received!");})app.listen(5000, (req, res)=>{console.log("Server is listening on PORT 5000");});

Now you will be able to post data on backend and receive a response on press of the button.

Now we know how to handle cors error and solve it.

Subscribe and follow for more articles like this.

Get an email whenever Musab Abbasi publishes. (medium.com)

--

--

Musab Abbasi

Computer Science Graduate with MERN stack website development expertise.