Saturday, November 30, 2024
Google search engine
HomeLanguagesReactJS CORS Options

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:

Project structure

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

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();
 
    const baseurl = "https://jsonplaceholder.typicode.com/";
 
    useEffect(() => {
        axios.get(`${baseurl}posts`).then((response) => {
            setPokemon(response.data);
            // console.log(response.data);
            setLoading(false);
        });
    }, []);
 
    if (isLoading) {
        return (
            <div className="App">
                <h1 className="neveropen">neveropen</h1>
                <div>Loading...</div>
            </div>
        );
    } else
        return (
            <div className="App">
                <h1 className="neveropen">neveropen</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;


Javascript




// Filename - index.js
 
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
 
const root = ReactDOM.createRoot(
    document.getElementById("root")
);
root.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>
);


CSS




/* App.css */
.App {
    text-align: center;
}
.neveropen {
    color: green;
}
 
.container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
}
 
.item {
    margin-top: 1%;
    max-width: 25rem;
    text-align: left;
}


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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments