-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
60 lines (43 loc) · 1.61 KB
/
server.js
File metadata and controls
60 lines (43 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
require('dotenv').config();
const express = require('express');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 8080;
// 1. JSON Parsing Middleware
app.use(express.json());
// Custom Middleware to Log Requests
const requestLogger = (req, res, next) => {
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] ${req.method} ${req.originalUrl} - Body: ${JSON.stringify(req.body)}`);
next(); // IMPORTANT: Call next() to pass control to the next middleware or route handler
};
app.use(requestLogger); // Apply the middleware to all requests
// Serve static HTML page (optional, but good practice for static assets)
// Access this via http://localhost:PORT/static.html
app.use(express.static(path.join(__dirname)));
// 2. GET / - "My Week 2 API!"
app.get('/', (req, res) => {
res.send("My Week 2 API!");
});
// 3. POST /user - Accepts {name, email}; responds "Hello, [name]!" (with error handling)
app.post('/user', (req, res) => {
const { name, email } = req.body;
if (!name || !email) {
// Error handling: Respond with 400 Bad Request
return res.status(400).send({
error: 'Both name and email are required in the request body.'
});
}
// Success response
res.send(`Hello, ${name}!`);
});
// 4. GET /user/:id - "User [id] profile"
app.get('/user/:id', (req, res) => {
const userId = req.params.id; // Get the ID from the URL parameter
// Success response
res.send(`User ${userId} profile`);
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});