0
0
Expressframework~30 mins

Why CORS matters for APIs in Express - See It in Action

Choose your learning style9 modes available
Why CORS Matters for APIs
📖 Scenario: You are building a simple Express API that will be accessed by a web page hosted on a different domain. To allow this, you need to understand and configure CORS (Cross-Origin Resource Sharing) properly.
🎯 Goal: Build a basic Express API server that allows cross-origin requests from a specific domain using CORS middleware.
📋 What You'll Learn
Create an Express app with a single GET route at /data that returns JSON data.
Add a configuration variable to specify the allowed origin for CORS.
Use the cors middleware with the allowed origin configuration.
Start the Express server listening on port 3000.
💡 Why This Matters
🌍 Real World
APIs often serve data to web pages hosted on different domains. Browsers block cross-origin requests by default for security. CORS lets you specify which domains can access your API safely.
💼 Career
Understanding and configuring CORS is essential for backend developers working with APIs that serve frontend applications on different domains or ports.
Progress0 / 4 steps
1
Set up Express app with a GET route
Create an Express app by requiring express and calling express(). Then add a GET route at /data that sends JSON { message: 'Hello from API' }.
Express
Need a hint?

Use app.get('/data', (req, res) => { ... }) to create the route.

2
Add allowed origin configuration
Create a constant called allowedOrigin and set it to the string 'http://example.com' to specify the allowed domain for CORS.
Express
Need a hint?

Define allowedOrigin as a string with the exact URL.

3
Use CORS middleware with allowed origin
Require the cors package and use it as middleware in the Express app with an options object setting origin to allowedOrigin.
Express
Need a hint?

Use app.use(cors({ origin: allowedOrigin })) to enable CORS for the allowed origin.

4
Start the Express server
Add app.listen to start the server on port 3000 with a callback that does nothing.
Express
Need a hint?

Use app.listen(3000, () => {}) to start the server.