What is ExpressJS, why it is needed, a brief comparison with other frameworks and code examples
http
module, which allows us to create an HTTP server on a TCP connectionnode > console.log(http.STATUS_CODES)
Fast, unopinionated, minimalist web framework for Node.js
http
module to make building servers not so hard.http
and there are other frameworks that sit on top of Express (e.g. Kraken, Sails, LoopBack), so there’s a lot of abstraction. Express is a good common ground to startHere’s how the code looks for a basic server in Express. With three lines of code you can have a server with two routes
1// setup a server with Express
2const express = require('express')
3const app = express()
4
5// on GET request to the URL
6app.get('/todos', (request, response) => {
7 // for any GET requests to /todos, run this code
8})
9
10// on POST request to the same URL
11app.post('/todos', (request, response) => {
12 // for any POST requests to /todos, run this code
13})
14
15// start server on port 3000
16app.listen(3000, () => {
17 console.log('Example app listening on port 3000!')
18})
Here’s how it would’ve looked with Node’s http
module
1// setup a server with Node's builtin http module
2const http = require('http')
3const port = 3000
4
5const requestHandler = (request, response) => {
6 console.log(request.url)
7 response.end('Hello Node.js Server!')
8}
9
10const server = http.createServer(requestHandler)
11
12server.listen(port, (err) => {
13 if (err) {
14 return console.log('something bad happened', err)
15 }
16
17 console.log(`server is listening on ${port}`)
18})
req
and res
are short for request and response. They’re just objects in teh callback that we have access to, and the callback that gives us so much flexibility and so much powerHere’s an example TODOs API
1let todos = [
2 'Finish this course',
3 'Make some coffee',
4 'Feed the fish',
5 'Wash the car'
6]
7
8app.get('/', (req, res) => {
9 res.send('Hello there, this is my todos app. Go to /todos to get all todo items')
10})
11
12app.get('/todos', (request, response) => {
13 // send back a JSON response
14 response.json(todos)
15})
16
17app.post('/todos', (req, res) => {
18 let todo = req.body.todo
19
20 todos.push(todos)
21 // res.send() will convert to JSON as well
22 // but req.json will convert things like null and undefined to JSON too although it's not valid
23 res.send(todo)
24})
25
26// get the response from the route
27app.get('/todos/:id', (req, res) => {
28 let todo = _.find(todos, {id: req.params.id})
29
30 res.json(todo)
31})
res.json()
will convert to JSON everything, including null
and undefined
, which are not exactly valid values..