Created
September 30, 2019 03:56
-
-
Save harrisonmalone/0cf82a1b8f231690477bfe8980eaff5d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const express = require('express'); | |
| const morgan = require('morgan'); | |
| const path = require('path'); | |
| // makes an instance of an express app | |
| const app = express(); | |
| // what is a port | |
| const PORT = 5000; | |
| // app.use means for every single route, use the morgan function | |
| // middleware | |
| app.use(morgan('tiny')) | |
| // in memory database | |
| const books = [ | |
| { | |
| id: 1, | |
| name: 'harry potter 1', | |
| author: 'jk rowling', | |
| movie: true | |
| }, | |
| { | |
| id: 2, | |
| name: 'brave new world', | |
| author: 'aldous huxley', | |
| movie: false | |
| } | |
| ] | |
| // 1. | |
| app.get('/books', (req, res) => { | |
| res.send(books) | |
| }) | |
| // 2. and 3. | |
| app.get('/books/:id', (req, res) => { | |
| const id = req.params.id | |
| // .find, Rails .find method | |
| const foundBook = books.find((book) => { | |
| return book.id === Number(id) | |
| }) | |
| if (!foundBook) { | |
| res.status(404).send({message: 'error'}) | |
| } else { | |
| res.send(foundBook) | |
| } | |
| }) | |
| app.get('/send-html', (req, res) => { | |
| const options = { | |
| root: path.join(__dirname, 'public'), | |
| } | |
| res.sendFile('index.html', options) | |
| }) | |
| // TODO | |
| // 1. How might we make an endpoint to access all of these books? | |
| // 2. How might we make an endpoint to access one of these books? | |
| // 3. How might we send a 404 message if the book doesn't exist? Look up res.status for this. | |
| // 4. How do you send an HTML file back to the client? | |
| // listening on port 5000 | |
| app.listen(PORT, () => console.log(`listening on port ${PORT}`)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment