I’ve written a couple of posts on how to use http modules, because when I started getting into coding with Node, I felt like I needed to learn the native APIs to evaluate the technology better. The understanding gave me a glimpse of the design decisions that Node has made over the years that made it so great. Knowing the native implementation made it clear to me at the time that this was going to be a technology that would play a significant role in web development. I wasn’t wrong. By investing my time in Node, I had a head start on the technology and benefited a lot from it in my career in the past few years.
Do not write your app with the native Node https module.
Here are the reasons:
Abstractions in frameworks are really good.
With Express.js, you can use
app.get(), you can use
app.all(), you can use
app.all('*'), you can get whatever you want. 🎶
Want to handle files? Add multer.
Want to write a socket server? Use socket.io.
Frameworks do a lot of the heavy lifting for you.
There are countless things you wouldn’t want to handle most of the time. Do you want to handle each individual chunks of strings that gets sent to your server? Do you need a different function to handle when you’re receiving data, and when the data ends? Do you want to write your own helpers to handle input methods? No? Use a framework.
Express.js (with body-parser) also parses JSON request body for you and convert it into an object. You don’t need to morph from a string input.
There’s a myriad of edge cases Express.js handle for you,
app.get('/data') is the same as
app.get('/data/'). No more of that
if (req.url === '/data') stuff that throws an error left and right.
The same http(s) module is used in sending and handling network request.
This is straightforward after understanding how web servers work but sure is confusing when you’re figuring out the syntax for just building a simple web server.
The Node API doc is better as a reference doc, not a getting started guide.
You won’t know what you need to read to get to what you want when learning Node.
When should one use Node’s native http module?
In most cases, only use it to mock a server in tests in projects you don’t have a framework like Express.js installed.