0
0
Node.jsframework~30 mins

CORS configuration in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
CORS Configuration in Node.js
📖 Scenario: You are building a simple Node.js server that will serve data to a frontend running on a different domain. To allow the frontend to access your server's resources, you need to configure CORS (Cross-Origin Resource Sharing) properly.
🎯 Goal: Set up a Node.js server using Express and configure CORS to allow requests only from http://example.com.
📋 What You'll Learn
Create a basic Express server
Install and use the cors middleware
Configure CORS to accept requests only from http://example.com
Add a simple GET route that returns a JSON message
💡 Why This Matters
🌍 Real World
Many web applications have frontend and backend on different domains. Configuring CORS properly allows secure communication between them.
💼 Career
Backend developers often need to configure CORS to enable frontend apps to access APIs safely and correctly.
Progress0 / 4 steps
1
Set up Express server
Create a variable called express that requires the express package. Then create a variable called app by calling express().
Node.js
Need a hint?

Use require('express') to import Express and call it to create the app.

2
Import and configure CORS middleware
Create a variable called cors that requires the cors package. Then create a variable called corsOptions that is an object with the key origin set to the string 'http://example.com'.
Node.js
Need a hint?

Use require('cors') to import CORS and define corsOptions with the origin set to 'http://example.com'.

3
Apply CORS middleware with options
Use app.use() to apply the cors middleware with the corsOptions object as its argument.
Node.js
Need a hint?

Call app.use() with cors(corsOptions) to enable CORS with your settings.

4
Add a GET route and start server
Add a GET route on '/' using app.get() that sends a JSON response with { message: 'Hello from server' }. Then start the server on port 3000 using app.listen().
Node.js
Need a hint?

Use app.get() to create the route and app.listen(3000) to start the server.