Skip to content

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.

var https = require('https’)

A GET request is pretty easy:

var https = require('https')
var req = https.request({
  hostname: 'somewhere.com',
  path: '/',
  port: 443,
  method: 'GET'
}, (res) => {
  var str = ''

  res.on('data', function (chunk) {
    str += chunk
  })

  res.on('end', function () {
    // Do stuff with your data (str)
  })
})

req.end()

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:

var https = require('https'),
  querystring = require('querystring')

var postData = querystring.stringify({
  data: 1,
  foo: 'bar'
})

var req = https.request({
  hostname: 'somewhere.com',
  path: '/acceptingData',
  port: 443,
  method: 'POST',
  headers: {'content-type' : 'application/x-www-form-urlencoded'}
}, (res) => {
  var str = ''

  res.on('data', function (chunk) {
    str += chunk
  })

  res.on('end', function () {
    // Do stuff (if you want)
  })
})

req.write(postData)
req.end()

Anyhow, not that bad! Hopefully this helps someone else 😀

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.