Express.js - Library for Routing Web Requests to Handler
Express.js is a JavaScript library that simplifies the process of registering endpoints with the web server so that the requests from your JavaScript code on the client are routed to the correct code within the Web API.
Basic Web Server
const express = require('express');
const app = express();
app.get('/', (req, res)=> {
res.send('Hello World!');
// req: HTTP request:
// URL parameters, query string, data in
// request body
// res: HTTP response: what you send back to the client
// JSON data, render a template, redirect, etc.
})
const port = 3000;
app.listen(port, ()=> {
console.log(`Server started on port ${port}`)
});
Testing Web API - VS Code Rest Client Extension
This is a great extension that allows you to execute web APIs within VS Code.
Create a file named server.rest at the top level of your project. A "Send Request" will appear above the GET command. Click it to execute the request and an output window will show the results.
Install JSON Viewer
GET http://localhost:3000
###
install nodemon
nodemon auto-detects changes to the source files in the project and automatically restarts the server. Use the "-D" option to install it as a dev dependency, so it won't be included in the production modules.
And when we modify the source code, we just need to refresh the web browser instead of restarting the node server.
Static Files - public folder
Create a folder named public at the top-level of your project and express will automatically serve requests for static files in that folder. HTML and CSS are examples of files that would go here.
// GET all
app.get('/api/animals', (req, res)=>{
res.json(zoo.animals);
});
// GET single member by id
app.get('/api/animals/:id', (req, res)=>{
const id = parseInt(req.params.id);
const animal = zoo.animals.find(x=>x.id===id);
res.json(animal);
});
Express Middleware
// middleware will be run every time a
// requests comes in.
const logger = (req, res, next) => {
// do whatever you want here and then
// pass the request on to the next middleware
// in the pipeline
next();
}
// initialize middleware
app.use(logger);
Express Routes
Express routes allow you to move your handlers into separate files. Create a new directory named "routes" and create a file named "animals.js" within it. Move the following code to the new files.
routes/animals.js
const express = require('express');
const router = express.Router();
const zoo = require('../data/zoo');
// GET all
router.get('/', (req, res)=>{
res.json(zoo.animals);
});
// GET single member by id
router.get('/:id', (req, res)=>{
const id = parseInt(req.params.id);
console.log(id);
const animal = zoo.animals.find(x=>x.id===id);
if (animal) {
res.json(animal);
}
else {
res.status(400).json({msg: `no animal with id ${id}`})
}
});
module.exports = router;
const express = require('express');
const path = require('path');
const app = express();
app.use('/api/animals', require('./routes/animals'))
const port = 3000;
app.listen(port, ()=> {
console.log(`Server started on port ${port}`)
});