0
0
Expressframework~30 mins

Configuring allowed origins in Express - Try It Yourself

Choose your learning style9 modes available
Configuring Allowed Origins in Express
📖 Scenario: You are building a simple Express server that will accept requests only from certain websites. This helps keep your server safe by allowing only trusted websites to talk to it.
🎯 Goal: Build an Express server that uses a list of allowed origins to control which websites can access it.
📋 What You'll Learn
Create an Express app
Define a list of allowed origins
Write middleware to check the request origin against the allowed list
Set the CORS headers only if the origin is allowed
💡 Why This Matters
🌍 Real World
Many web servers need to control which websites can access their resources to prevent unauthorized use and security risks.
💼 Career
Understanding how to configure allowed origins and CORS headers is essential for backend developers working with APIs and web servers.
Progress0 / 4 steps
1
Create the Express app
Write code to import express and create an Express app called app.
Express
Need a hint?

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

2
Define allowed origins list
Create a constant array called allowedOrigins with these exact strings: 'http://example.com' and 'http://localhost:3000'.
Express
Need a hint?

Use an array with the exact URLs as strings.

3
Add middleware to check origin
Add middleware to app that checks if req.headers.origin is in allowedOrigins. If yes, set the header Access-Control-Allow-Origin to that origin. Use app.use and a function with parameters req, res, and next.
Express
Need a hint?

Use app.use to add middleware. Check if origin is in allowedOrigins and set the header accordingly.

4
Start the server
Add code to make app listen on port 4000 using app.listen.
Express
Need a hint?

Use app.listen(4000) to start the server on port 4000.