You are currently viewing Node.js and CORS (Cross-Origin Resource Sharing)

Node.js and CORS (Cross-Origin Resource Sharing)

  • Post author:
  • Post category:Nodejs
  • Post comments:0 Comments
  • Post last modified:February 18, 2024

In this tutorial, we’ll explore how to enable CORS (Cross-Origin Resource Sharing) in a Node.js application. CORS is a security feature implemented by web browsers to restrict cross-origin HTTP requests initiated from scripts running in the browser. It allows servers to specify who can access their resources, thereby preventing unauthorized access to sensitive data.

Prerequisites:

  • Basic knowledge of Node.js and JavaScript.
  • Node.js installed on your machine.

Step 1: Set up a Node.js project
First, let’s create a new directory for our project and initialize a new Node.js project using npm.

mkdir node-cors-example
cd node-cors-example
npm init -y

Step 2: Install required packages
We’ll need the express package to create a simple HTTP server and the cors package to enable CORS.

npm install express cors

Step 3: Create the Node.js server
Create a file named server.js in your project directory and add the following code:

Step 4: Test the server
Run the server by executing the following command in your terminal:

node server.js

Open your web browser and navigate to http://localhost:3000/api/data. You should see the JSON response with the message “Hello from the server!”.

Step 5: Test CORS functionality
To test CORS functionality, create an HTML file named index.html in your project directory with the following content:

Open the index.html file in your web browser. When you click the “Get Data” button, it should fetch data from the Node.js server and display the message “Hello from the server!”.

Conclusion
In this tutorial, you learned how to enable CORS in a Node.js application using the cors middleware package. CORS allows you to securely access resources from different origins and is essential for building modern web applications with cross-origin requests.

Leave a Reply