Skip to content

Instantly share code, notes, and snippets.

@codecademydev

codecademydev/server.js Secret

Created Aug 4, 2020
Embed
What would you like to do?
Codecademy export
const express = require('express');
const morgan = require('morgan');
const app = express();
const { quotes } = require('./data');
const { getRandomElement } = require('./utils');
const PORT = process.env.PORT || 4001;
app.use(express.static('public'));
//Random quote (GET)//
app.get('/api/quotes/random', (req, res, next) => {
res.send({quote: getRandomElement(quotes)})
});
//All quotes or By author (GET)//
app.get('/api/quotes', (req, res, next) => {
if (req.query.person !== undefined){
const byAuthor = quotes.filter(quote => quote.person === req.query.person);
res.send({quotes: byAuthor});
} else {
res.send({quotes});
}
});
//Add new quote (POST) //
app.post('/api/quotes', (req, res, next) => {
const newObj = {
quote: req.query.quote,
person: req.query.person
};
if (newObj.quote && newObj.person){
console.log(newObj);
quotes.push(newObj);
res.send({quote: newObj});
} else {
console.log('failed')
res.status(400).send();
}
})
app.listen(PORT, () => {
console.log(`Server listening to port ${PORT}`)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.