It's time to get some practice setting up an express server and writing a few routes. Feel free to test these routes either with the browser's navbar, a small node
script using axios
or a toy react app with connected with axios
. We'll also be working with the data array in fruits.js
to practice our routes.
Fork
andclone
this repocd
into the repotouch index.js
to create an entry point for your server- Run
npm init -y
to initialize your project as aNode.js
project - Install express with
npm i express
- We'll install
nodemon
withnpm i nodemon --save-dev
to save it as a dev dependency - Add
start
anddev
scripts topackage.json
that will run on your server's entry point:"scripts": { "start": "node index.js", "dev": "nodemon index.js" }
Let's write the boilerplate for an express server:
-
First, import
express
by requiring it at the top ofindex.js
with:const express = require('express');
-
Go ahead and define a
PORT
constant variable:const PORT = process.env.PORT || 3001;
-
Init an
app
instance below your initial imports:const app = express();
-
You may want to create some space between your app instance and the step below since we'll be writing routes in between them shortly.
-
Finally, bind the app to a port with
app.listen()
at the bottom of the file:app.listen(PORT, () => console.log(`Serving up delicious fruits on port ${PORT} 🍒`))
Now start the server from the terminal with npm run dev
. If all goes well, you should see the message from the console log above in the console. Don't stop the server until you are done writing code or unless you just want to restart it. If you save the index.js
file the server should automatically re-load the changes and restart since we're using nodemon
in our dev
script in package.json
.
Start off by defining a simple GET
route:
app.get('/hello', (req, res) => {
console.log('hello world!')
res.send('hello world!')
})
GET
/greet/:name
should return a greeting with the supplied name, e.g., 'Why hello there, <name>!'
Recall you can access the URL parameters with req.params
GET
/five
should return an array of the numbers from 1-5
Remember that you can create variables above your response
GET
/fruits
should return an array with all the fruits.
Let's add a route that returns an array of fruits when we access the route
app.get('/fruits', (req, res) => {
//your code here
res.send()
})
Now let's add a route that takes a route parameter name
and retrieves the fruit that matches the supplied name.
app.get('/fruits/:name', (req, res) => {
//your code here
// HINT - you can use a higher-order array method
})
With a working route to show an array of fruits, and an individual fruit, lets take this same concept and make another route that returns an array of vegetables, then try to create a route for the individual ones
GET
/fruits/sort
should return the fruits array sorted alphabetically using .sort().
app.get('/fruits/sort', (req, res) => {
// implement sort
res.send()
})
Secret Bonus
What if we wanted to add a catch-all route to our express app so some crazy fruit ninja doesn't go breaking things?
To prepare for that, let's add this quick route at the very bottom of our routes, just above app.listen()
app.get('*', (req, res) => {
res.send('404 Not Found')
})
A couple important things to note:
- The
*
used for a route will cover any route request made to our server, meaning that it will respond with this 404 message for any URL param chained on tohttp://localhost:3001
- That being said, since it will respond to any route, we put it at the bottom of our server, so our other routes are still accessible while routes that don't exist will be sent to an error message
- Use it wisely if you choose to
- Pull Request must be submitted utilizing these guidelines: PR Guidelines