Open In App

How to Handle CORS in JavaScript ?

Cross-Origin Resource Sharing (CORS) is a browser-level security feature that disallows the requests (by default) to be made between different origins, i.e., a frontend client requesting a backend server that is deployed on a different origin or domain. We can bypass or allow the requests that are made cross-origin with the help of different methods. In this article, we will learn how to handle CORS in JavaScript with the help of some code examples.

Handling CORS using Express server

In this approach, we will create and use the NodeJS and expressJS servers to handle the CORS requests made to them. We can set the "Access-Control-Allow-Origin" in the response object header for every request that is sent to it, to allow the requests from any origin.

Example:

Setup the application:

First, install the required packages for the application using the below steps:

npm init -y
npm i express

Create the index.js file:

Now, create the index.js file, and setup the express server. In the same file, allow the "Access-Control-Allow-Origin" response header to every requests that are made to it.

const express = require('express');
const app = express();

app.use((req, res, next) => {
    res
        .header('Access-Control-Allow-Origin',
            '*');
    res
        .header('Access-Control-Allow-Methods',
            'GET, POST, PUT, DELETE');
    res
        .header('Access-Control-Allow-Headers',
            'Origin, X-Requested-With,Content-Type, Accept');
    next();
});

app.get('/data', (req, res) => {
    res
        .json
        (
            {
                name: 'Brazil',
                currency: 'BRL'
            }
        );
})

app.listen(3000, () => {
    console
        .log('Server is running on port 3000');
});

Run the express API server

Start the server using the below command

npm start

Creating a vanilla JS application to consume the above API server endpoint

Run the below commands inside the terminal to create a basic structure for creating our javascript application

mkdir cors-test
cd cors-test
touch index.html

The project structure would look like below:

Project structure:
file

Now, modify the index.html file in the project structure to fetch the data from the express API server, and display that data in the UI.

Filename: index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>Handle CORS in javascript</title>
</head>

<body>
    <h1>Data from Server</h1>
    <div id="data"></div>

    <script>
        document
            .addEventListener('DOMContentLoaded', () => {
                const dataContainer = document
                    .getElementById('data');

                fetch('http://localhost:3000/data')
                    .then(response => response.json())
                    .then(data => {
                        const { name, currency } = data;
                        dataContainer
                            .innerHTML = `
            <p>Name: ${name}</p>
            <p>Currency: ${currency}</p>
          `;
             })
             .catch(error => {
              console
              .error('Error fetching data:', error);
               dataContainer
              .innerHTML = '<p>Error fetching data. Please try again later.</p>';
                    });
            });
    </script>
</body>

</html>

Run the vanilla javascript application:

Now, open the index.html file created above, to see the output in the browser.

Output:

cors

Article Tags :