Initialize the project and install and save express to package.json
1npm init -y
2npm i -S express
Here’s the code for a very basic server up and running
1const express = require('express')
2const app = express()
3
4app.get('/', function (req, res) {
5 res.send('Bonjour la monde!')
6})
7
8const server = app.listen(3001, function () {
9 console.info(`Server running at http://localhost:${server.address().port}`)
10})
install nodemon
and add npm scripts to package.json
1npm i -D nodemon
1"scripts": {
2 "start": "node index.js",
3 "dev": "nodemon index.js"
4}
app.METHOD(PATH, HANDLER)
For every route, you need a path and a route handler function (callback function) for that path
'home'
), path pattern (*.json
), regex, or an array.1app.get('/yo', function (req, res) {
2 res.send('HEYO!')
3})
whenever someone visits /yo
, they’ll get a HEYO! in response.
You can pass in multiple handlers, like so
1// function verifyUser (req, res, next) { .. }
2
3app.get('/:username', verifyUser, function (req, res) {
4 let user = req.params.username
5 rese.render('user', {
6 user: user,
7 address: user.location
8 })
9})
Response res
in our callback route handler is an object, it has it’s own methods, like .send()
, .redirect()
, .status()
etc. The res
object is an enhanced version of Node’s own response object and supports all built-in fields and methods.
1// Some example responses
2
3// send a very simple string response
4res.send('Hello')
5
6// send an 404
7res.status(404).send(`No username ${req.params.username} found`)
8
9// redirect to a page
10res.redirect(`/error/${req.params.username}`)
11
12// download a resource
13app.get('*.json', function (req, res) {
14 // whenever someone goes to a path ending in .json, download the corresponding file
15 // e.g. i go to /mojojojo.json, i download the file at /users/mojojojo.json
16 res.download(`./users/${req.path}`)
17 // You can optionally provide a second param as file name
18 // res.download('filePath', 'fileName')
19 res.download(`/users/${req.path}`, 'virus.exe`) // buahahaa
20})
21
22// JSON, send data back as json, like an API server
23res.json(foo)
The captured values are populated in the req.params
object, with the name of the route parameter specified in the path as their respective keys.
1app.get('/users/:userId/books/:bookId', function (req, res) {
2 res.send(req.params)
3})
Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }