Creating A Vanilla Node Server

All these tutorials using express! It’s time to use the http module to make a server and do the hard work for once.


First lets require the native http module.

const http = require('http');

We don’t need to npm install this because it comes along with node.

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

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

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

http.createServer((request, response) => { 
response.end('Hello!');
}).listen(8080, () => console.log("Server is listening on port 8080"));

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 use 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") {
// GET response
} else if (request.method === "POST") {
// POST response
} else {
// Others
}
} else {
// Other...
}
}).listen(8080, () => console.log("Server is listening on port 8080"));

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

http.createServer((request, response) => {  
if (response.method === "POST") {
response.writeHead(201);
// response back with data
}
}).listen(8080, () => console.log("Server is listening on port 8080"));

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