forked from CodeYourFuture/quote-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
41 lines (35 loc) · 1.27 KB
/
server.js
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
// server.js
// This is where your node app starts
//load the 'express' module which makes writing webservers easy
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
//load the quotes JSON
const quotes = require("./quotes.json");
// Now register handlers for some routes:
// / - Return some helpful welcome info (text)
// /quotes - Should return all quotes (json)
// /quotes/random - Should return ONE quote (json)
app.get("/", function (request, response) {
response.send("Matilda's Quote Server! Ask me for /quotes/random, or /quotes");
});
//START OF YOUR CODE...
app.get("/quotes", (request, response) => {
response.send(quotes);
});
app.get("/quotes/random", (request, response) => {
response.send(pickFromArray(quotes));
});
//...END OF YOUR CODE
//You can use this function to pick one element at random from a given array
//example: pickFromArray([1,2,3,4]), or
//example: pickFromArray(myContactsArray)
//
function pickFromArray(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
//Start our server so that it listens for HTTP requests!
const listener = app.listen(process.env.PORT, function () {
console.log("Your app is listening on port " + listener.address().port);
});