July 2017
Intermediate to advanced
656 pages
16h 1m
English
We only need one module, the http module.
Let's require it:
const http = require('http')
Now we'll define a host and port which our HTTP server will attach to:
const host = process.env.HOST || '0.0.0.0' const port = process.env.PORT || 8080
Next, let's create the actual HTTP server:
const server = http.createServer((req, res) => { if (req.method !== 'GET') return error(res, 405) if (req.url === '/users') return users(res) if (req.url === '/') return index(res) error(res, 404) })
In the request handling function we passed to the http.createServer method, we reference three other functions, error, users, and index.
First let's write our route handling functions:
function users (res) { res.end('{"data": [{"id": 1, "first_name": ...