Creating A Vanilla Node Server

All these tutorials using express, but what does express use? It’s time to use the http module to make a vanilla server to get a better understanding of node and http.


First lets require the native http module.

const http = require('http');

We don’t need to npm install anything because the http module comes along with node.

Now lets create our server and have it listen on port 8080.

const PORT = 8080;
const server = http.createServer((request, response) => {
});
server.listen(PORT, () => console.log("Server is listening on port %s", PORT));

Great, now if we run this with node, we’ll have our server up. Except theres a problem. If we tried to connect or make any type of requests to the server, nothing would happen because right now we aren’t responding on any requests.

http.createServer((request, response) => { 
response.end('Hello!');
});

Now when ever we make any request to our server, we will get back “Hello!”.

This is great, but we want to execute different actions based on the type of request method we get. Inside the request object, we can grab the url and method properties to determine what we want to respond with.

http.createServer((request, response) => { 
if (request.url === "/my/route") {
if (request.method === "GET") {
// some GET response
} else if (request.method === "POST") {
// some POST response
} else {
// others... (PUT, DELETE, etc...)
}
} else {
// any other route...
}
});

We can also use the writeHead function to add extra information in our response.

http.createServer((request, response) => {  
if (response.method === "POST") {
response.writeHead(201);
// response back with data
}
});

Awesome! Now we have dove a little bit into how to use the http module and have created a server without express.