-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquote.js
More file actions
45 lines (33 loc) · 1.04 KB
/
Copy pathquote.js
File metadata and controls
45 lines (33 loc) · 1.04 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
//the env connection should be at the top
const dotenv = require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const Quote = require("./models/quote");
const PORT = 3000;
const app = express();
// connect to mongo
mongoose.connect(process.env.MONGO_URL)
.then (() => console.log('Mongo coneccted'))
.catch(err => console.log(err));
//route
app.get("/", async(req,res) =>{
try {
const quotes = await Quote.find();
if (quotes.length === 0){
return res.send('No quotes found!');
}
const randomIndex = Math.floor(Math.random() * quotes.length);
const randomQuote = quotes[randomIndex];
res.send (`
<h2>Today's quote</h2>
<p>"${randomQuote.text}"</p>
<p><strong>- ${randomQuote.author}</strong></p>
`);
} catch (error){
res.status(500).send("Error fetching quotes");
}
});
//start server
app.listen(PORT,() => {
console.log(`Server running on port ${PORT}`);
});