Open In App

Use of CORS in Node.js

Last Updated : 12 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The word CORS stands for "Cross-Origin Resource Sharing". Cross-Origin Resource Sharing is an HTTP-header based mechanism implemented by the browser which allows a server or an API(Application Programming Interface) to indicate any origins (different in terms of protocol, hostname, or port) other than its origin from which the unknown origin gets permission to access and load resources. The cors package available in the npm registry is used to tackle CORS errors in a Node.js application. 

Why Use CORS?

The reasons to use CORS in the application are

  • Security: CORS helps to prevent malicious websites from accessing sensitive information on your server.
  • Resource Sharing: It allows controlled access to resources on a server from a different origin, enabling web applications to make API requests to external services.

Let's understand using an example.

Steps to Implement/Enable CORS in Node App

Step 1: Check If Node is installed in your system

As the CORS package is available in npm(node package manager) that Node.js third-party package, we must have Node.js installed in our local system. To verify type the following command in the terminal.

node -v

The command will show the version of Node.js installed in your system. If it gives some error, make you install Node.js properly, for that follow this link.

Step 2:  Project setup and folder structure. First, create a folder in your system named "geeksforgeeks" and move to the folder using a command prompt. Use the following command to do so.

mkdir geeksforgeeks && cd geeksforgeeks

Inside that folder create two separate folders: client and server(using same mkdir command). Inside the client, the folder creates index.html and script.js files. Inside the server folder type the following command to generate the package.json file :

npm init

Now, create an index.js file inside the server folder to write the server-side logic. Our current folder structure should look like this.

Project Structure: It will look like the following.

Step 3: Now inside the same directory, install necessary packages( express and cors) using the following command :

npm install express cors

The Updated dependencies in the package.json file:

"dependencies": {
    "cors": "^2.8.5",
    "express": "^4.19.2"
}

Step 4: This is the code inside the index.html file. This is the main HTML code that will be shown to the client in the browser.

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sample webpage</title>
    <script src="script.js" defer></script>
</head>

<body>
    <h1>Sample Webpage</h1>
    <div id="data"></div>
</body>

</html>

<!-- Frontend will be running on port 5500. -->
JavaScript
document.addEventListener("DOMContentLoaded", () => {
    fetch('http://localhost:3000/api/data')
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            document.getElementById('data').innerText = JSON.stringify(data, null, 2);
        })
        .catch(error => {
            console.error('There has been a problem with your fetch operation:', error);
        });
});

We are allowing requests from some particular origins using the corsOptions object.

let corsOptions = {
    origin : ['http://localhost:5500'],
}    
# this corsOptions object enables CORS action for all origins running on port 5500 only.
# So if an application is running on any port other than 5000(own origin) and 5500, 
  no CORS action will be enabled.

Inside the Server Directory:

Node
// Filenamr index.js 

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

// CORS options to allow requests from frontend running on port 5500
const corsOptions = {
    origin: 'http://localhost:5500', // Allow only requests from this origin
    methods: 'GET,POST', // Allow only these methods
    allowedHeaders: ['Content-Type', 'Authorization'] // Allow only these headers
};

// Use CORS middleware with specified options
app.use(cors(corsOptions));

app.get('/api/data', (req, res) => {
    const responseData = {
        message: "Hello, GFG Learner",
        articleData: {
            articleName: "How to send JSON response from NodeJS",
            category: "NodeJS",
            status: "published"
        },
        endingMessage: "Visit Geeksforgeeks.org for more"
    };
    res.json(responseData);
});

const port = 3000;
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});

Steps to Run: Use the following command in server directory and server will start on the port 3000.

node index.js

Output:

Node CORS Example
Node js Cors Example

Conclusion

CORS is crucial for security and functioning of web applications making cross-origin requests. In Node.js, the cors middleware for Express simplifies enabling and configuring CORS, allowing you to control resource sharing with fine-grained policies. This ensures that your API can be securely accessed by authorized web applications across different domains.


Next Article

Similar Reads