CORS Error in React.js

What is CORS?

When do we get a CORS error?

Identifying the issue

  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:
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

Getting Started

npx create-react-app frontend
mkdir backend
cd ./backend
npm init -y
npm install express body-parser nodemon
"start": "nodemon 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.listen(5000, (req, res)=>{console.log("Server is listening on PORT 5000");});
npm start
npm install axios

What is Axios

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
npm start

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;
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

npm install cors
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");});

--

--

Computer Science Graduate with MERN stack website development expertise.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Musab Abbasi

Computer Science Graduate with MERN stack website development expertise.