Get ready for your next interview with our comprehensive question library
const express = require('express');
const app = express();
const PORT = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
This creates a basic server that listens on port 3000 and responds with "Hello World!" when accessing the root route.
Middleware functions are functions that have access to the request object (req), response object (res), and the next middleware function in the application's request-response cycle. Middleware can execute code, modify req/res objects, end the request-response cycle, or call the next middleware.
// Custom middleware
app.use((req, res, next) => {
console.log('Time:', Date.now());
next(); // Call next to continue to the next middleware
});
app.use()
router.use()
app.get('/users', (req, res) => {
res.send('GET request');
});
app.post('/users', (req, res) => {
res.send('POST request');
});
app.put('/users/:id', (req, res) => {
res.send('PUT request');
});
app.delete('/users/:id', (req, res) => {
res.send('DELETE request');
});
The next()
function passes control to the next middleware function. If not called, the request will be left hanging. You can pass an error to next(err)
to trigger error handling middleware.
app.use((req, res, next) => {
if (req.headers.authorization) {
next(); // Continue to next middleware
} else {
next(new Error('Unauthorized')); // Trigger error handling
}
});
Use the built-in express.static
middleware:
// Serve files from 'public' directory
app.use(express.static('public'));
// Serve with virtual path prefix
app.use('/static', express.static('public'));
Upgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumAccess all premium content - interview questions, and other learning resources
We regularly update our features and content, to ensure you get the most relevant and updated premium content.
1000 monthly credits
Cancel anytime