Simple HTTP requests in Node (no packages)

This was surprisingly difficult to find, so I’m writing a wee blog post about it! I was working on a project recently (more on that soon!) and didn’t want to have any dependencies because $REASONS. And I needed to make some AJAX requests.

Most of the time in Node, it seems that require(‘request’) or another flavor of it is the solution to “how to make a simple HTTP request.” But of course, it’s not that difficult to make an HTTP request without syntactic sugar.

The first thing is to ask if you’re making an HTTP (port 80) or HTTPS (port 443) call. The package you require from Node will differ based on this. In my case I was making all HTTPS, so I used that. If you make an HTTP request, you’ll need to require that module, the same things should work.

Other than having to remember to do req.end() this isn’t much different from using the request module, in my humble experience.

A POST request has a couple changes. One you’ll expect is change method to method: ‘POST’. You’ll probably want to use the (also native) querystring module to format your post data. And then, don’t forget to include your content-type headers! Full sample: