Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
Essence of Node.js
Next article icon

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
Essence of Node.js

S

shinjanpatra
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • NodeJS-Questions

Similar Reads

  • Session Cookies in Node.js
    HTTP protocol: It is the backbone of the internet every single request from the client for particular contains several HTTP headers and that contains all the information of the request. This protocol is the foundation of the data exchange over the internet but the HTTP protocol is the stateless prot
    4 min read
  • Essence of Node.js
    Node.js or Node has a small core group of modules, commonly referred to as the Node Core that is exposed as the public Node API by using we write our applications or we can say that the Node Core implements the public Node API. Some examples of the modules present in the node core are: To work with
    8 min read
  • RESTful Routes in Node.js
    Routing: Routing is one of the most significant parts of your website or web application. Routing in Express is basic, adaptable, and robust. Routing is the mechanism by which requests (as specified by a URL and HTTP method) are routed(directed) to the code that handles them.  What is RESTful Routin
    4 min read
  • HTTPS in Node.js
    HTTP: When the data is transferred in HTTP protocol it just travels in the clear text format.  HTTPS: It simply encrypts the request from the browser to the web server, so it is tough to sniff that information. It basically works on two things:  SSL (Secure Socket Layer)TLS (Transport layer security
    3 min read
  • HTTP Cookies in Node.js
    Cookies are small data that are stored on a client side and sent to the client along with server requests. Cookies have various functionality, they can be used for maintaining sessions and adding user-specific features in your web app. For this, we will use cookie-parser module of npm which provides
    4 min read
  • Express.js | router.use() Function
    The router.use() function uses the specified middleware function or functions. It basically mounts middleware for the routes which are being served by the specific router. Syntax: router.use( path, function )Parameters: Path: It is the path to this middleware, if we can have /user, now this middlewa
    2 min read
  • Express.js vs KoaJS in Node.js
    Node.js: Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework and it’s not a programming language. Most of the people are confused and understand it’s a framework or a programming languag
    4 min read
  • Node.js DNS Complete Reference
    Node.js DNS is a node module used to do name resolution facility which is provided by the operating system as well as used to do an actual DNS lookup. Example: [GFGTABS] JavaScript <script> // Node.js program to demonstrate the // dns.resolve() method // Accessing dns module const dns = requir
    3 min read
  • HapiJS vs KoaJS in Node.js
    HapiJS Module: In order to use the hapiJS module, we need to install the NPM (Node Package Manager) and the following modules (on cmd). // Create package.json file >> npm init // Installs hapi module >> npm install @hapi/hapi --save Import hapiJS module: Import hapiJS module and store re
    3 min read
  • How to use SSL/TLS with Node.js ?
    TLS/SSL is used for establishing secure connections over the internet. Today, most websites use HTTPS to communicate with clients. HTTPS is basically HTTP running over TLS/SSL. Web clients like browsers alert users about websites that do not use HTTPS since such websites are vulnerable to cyber-atta
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences