-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
40 lines (31 loc) · 1002 Bytes
/
index.js
File metadata and controls
40 lines (31 loc) · 1002 Bytes
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
const express = require('express');
const dogFacts = require('./dog_facts.js');
const app = express();
app.set('port', process.env.PORT || 3000);
// GET /facts endpoint
app.get('/facts', (req, res) => {
const number = parseInt(req.query.number); //converting the query param to an int
// Check if number is provided and valid
if (isNaN(number)) {
// Return all facts if number is not provided
return res.json({ facts: dogFacts, success: true });
}
// Validation and print errors
if (number <= 0) {
return res.status(400).json({ success: false, message: 'Invalid number:' });
}
// Return facts based on the number requested
const factsToSend = dogFacts.slice(0, number);
// Send response
res.json({ facts: factsToSend, success: true });
});
// 404 - Not Found route
app.use((req, res) => {
res.type('text/plain');
res.status(404);
res.send("404 - Not Found");
});
// Start server
app.listen(app.get('port'), () => {
console.log("Express Server is Running");
});