How to Handle CORS in JavaScript ?
Last Updated :
08 Apr, 2024
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.
JavaScript
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:

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

Similar Reads
How to Hide API Key in JavaScript? The Process of Hiding API keys in JavaScript is crucial for securing our application and preventing unauthorized access. API Keys should not be exposed in client-side code because anyone can view the source code and misuse the keys. The primary goal is not accessible to end users.PrerequisitesJavaSc
1 min read
How to connect to an API in JavaScript ? An API or Application Programming Interface is an intermediary which carries request/response data between the endpoints of a channel. We can visualize an analogy of API to that of a waiter in a restaurant. A typical waiter in a restaurant would welcome you and ask for your order. He/She confirms th
5 min read
How To Fetch And Parse RSS Feeds In JavaScript? RSS (Really Simple Syndication) feeds are widely used for sharing updates from websites in a standardized XML format. By fetching and parsing RSS feeds, you can access the latest content from blogs, news sites, and other platforms. In this article, weâll explore how to fetch and parse RSS feeds usin
4 min read
How to Use Handle Get Request in Express.js ? Express.js is a popular web application framework for Node.js, known for its simplicity and flexibility. One of the fundamental tasks in web development is handling HTTP requests, and GET requests are among the most common. This article will guide you through the process of handling GET requests in
2 min read
Fetch API in JavaScript The Fetch API is a modern interface in JavaScript that allows you to make HTTP requests. It replaces the older XMLHttpRequest method and provides a cleaner and more flexible way to fetch resources asynchronously. The Fetch API uses Promises, making it easier to work with asynchronous data.Syntaxfetc
6 min read
How to Make GET call to an API using Axios in JavaScript? Axios is a promise-based HTTP client designed for Node.js and browsers. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on GitHub. It can be imported in plain JavaScript o
3 min read