Creating an HTTP server
HTTP is the most prolific protocol in the application of the internet protocol suite. Node comes bundled with the core http
module which provides both client and server capabilities.
In this recipe, we're going to create an HTTP server from scratch.
Getting ready
To keep things interesting, our server is actually going to be a RESTful HTTP server, so let's create a folder called rest-server
, containing a file named index.js
.
How to do it...
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...