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.
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 allapp.get('/api/animals', (req, res)=>{res.json(zoo.animals);});// GET single member by idapp.get('/api/animals/:id', (req, res)=>{constid=parseInt(req.params.id);constanimal=zoo.animals.find(x=>x.id===id);res.json(animal);});
Express Middleware
// middleware will be run every time a// requests comes in.constlogger= (req, res, next) => {// do whatever you want here and then// pass the request on to the next middleware// in the pipelinenext();}// initialize middlewareapp.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
constexpress=require('express');constrouter=express.Router();constzoo=require('../data/zoo');// GET allrouter.get('/', (req, res)=>{res.json(zoo.animals); });// GET single member by idrouter.get('/:id', (req, res)=>{constid=parseInt(req.params.id);console.log(id);constanimal=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;
constexpress=require('express');constpath=require('path');constapp=express();app.use('/api/animals',require('./routes/animals'))constport=3000;app.listen(port, ()=> {console.log(`Server started on port ${port}`)});