1

ReactJS CORS Options

 1 month ago
source link: https://www.geeksforgeeks.org/reactjs-cors-options/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

ReactJS CORS Options

In ReactJS, Cross-Origin Resource Sharing or CORS requests refers to the method that allows you to make requests to the server deployed at a different domain. As a reference, if the frontend and backend are at two different domains, we need CORS there. 

Method to set up CORS requests in the React App

  • Using Axios: Axios always uses the base URL to start the request and the browser confirms that in the beginning HTTP OPTIONS requests by itself. Many times we need to pass tokens for authentication and the token which we are using is identified by Bearer. Now, the main part we need to pass is some additional headers for CORS named Access-Control-Allow-Credentials. This one is required because the browser needs to confirm the server that is allowed to access resources.
  • Using fetch: To use CORS in fetch we need to use the mode option and set it to cors.
const response = await fetch("https://api.request.com/api_resource", {
method: "GET",
mode: "cors", // Change the mode to CORS
headers: {
Authorization: `Bearer: ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
console.log(response.json());

Let’s create an application in React to demonstrate the above concept using Axios.

Steps to create the application:

Step 1: Create a React application using the following command:

npx create-react-app example

Step 2: After creating your project folder i.e. example, move to it using the following command:

cd example

Step 3: Here we are using the Axios library for fetching API data, we need to install that by using the command from the root directory.

npm i axios

Project Structure:

folderstructure.jpg

Project structure

Example: Demonstrating the CORS options in ReactJS. Write down the following code in index.js and App.js file.

  • Javascript
  • Javascript
// Filename - App.js
import React, { useEffect, useState } from "react";
import axios from "axios";
import "./App.css";
function App() {
const [isLoading, setLoading] = useState(true);
const [pokemon, setPokemon] = useState();
useEffect(() => {
axios.get(`${baseurl}posts`).then((response) => {
setPokemon(response.data);
// console.log(response.data);
setLoading(false);
});
}, []);
if (isLoading) {
return (
<div className="App">
<h1 className="geeks">GeeksforGeeks</h1>
<div>Loading...</div>
</div>
);
} else
return (
<div className="App">
<h1 className="geeks">GeeksforGeeks</h1>
<h3>React JS CORS Options</h3>
<h4>No CORS error in the console window</h4>
<div className="container">
{pokemon.map((e) => (
<div className="item" key={e.title}>
<div>
<b>Title: </b>
{e.title}
</div>
<div>
<b>Description: </b>
{e.body}
</div>
</div>
))}
</div>
</div>
);
}
export default App;

Step to run the application: Open the terminal and type the following command.

npm start

Output: We will see the following output on the browser screen.

We can see in the console that there is no CORS error. Therefore, we successfully handled the CORS in react.

Peek-2023-10-11-09-42

“This course was packed with amazing and well-organized content! The project-based approach of this course made it even better to understand concepts faster. Also the instructor in the live classes is really good and knowledgeable.”- Tejas | Deutsche Bank

With our revamped Full Stack Development Program: master Node.js and React that enables you to create dynamic web applications.

So get ready for salary hike only with our Full Stack Development Course.

Last Updated : 13 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK