Express Superheros (Index/Show)
... because Superheroes need REST Too
Learning Objectives
- Setting up a basic express server
Prerequisites
- JavaScript
- Express
Getting Started with a Basic Express App
- Create a new directory called
"superheroes"
cd
into superheroes- create a
server.js
file - perform an npm init, specify
server.js
as your entry point - install express
- inside
server.js
, require express and save it to a variable namedexpress
- create a variable named app, and set it equal to
express()
-
have app listen on port 3000
- once it's listening, log "Here to save the day..."
- test it by going to
http://localhost:3000
Creating Routes
- Create a variable called superheroes and set it to
[ 'Superman', 'Wonder Woman', 'Black Panther' ]
-
Create a route to
/superheroes
, which will be theindex
- The route should send the entire superheroes array
-
Create a route to
/superheroes/:index
, which will be theshow
route- The route should send the superhero that is at the index in the superheroes array as specified by req.params.index
Enhancing Data
-
Change the entries in the superheroes array so that each element in the array is an object
- E.g. Instead of 'superman' have:
{ name: "Superman", powers: ['flight', 'invulnerability', 'x-ray vision']}
- E.g. Instead of 'superman' have:
- Upgrade your
res.send
on theshow
route to send the superhero name as anh1
and then the powers asli
items in anul
( hint: use string interpolation or string concatenation ) - Writing HTML this way is really tedious and hard to read...I wonder if we'll learn a better way to do this soon?
Add Villians!
-
Bring in this data
[ { name: "Lex Luthor", powers: ["super brain"] }, { name: "Ares", powers: ["shape shifting", "teleporting"] }, { name: "Killmonger", powers: ["ability to fit in Black Panther's suit", "internet agreement that he looks badass"] } ]
- Render them in the index below our heros
- Render show routes for these guys, that have the powers listed (just like superheroes)
- On the show page of the superhero, show the villian's name (hint: the villians array index position matches the hero)
Hints:
- It's all just JavaScript! Do JS things to manipulate the 'data'
Friends
Let's do another rep with setting up an express server!
cd
back into the labs directory- create a directory called friends
- cd into friends
- Create a basic express app
- Create a variable inside
server.js
that is an array of your friends - Create
index
andshow
routes - Enhance the data so that each friend is an object with age, location, eyeColor, hairColor attributes
- The
index
should be a name that links to the show page - the
show
route should show all the details of your friend