Home > Net >  How to make request with Node http module
How to make request with Node http module

Time:12-14

How do I make get request to https://api.urbandictionary.com/v0/define?term=wat using http.request? When running this code, I'm getting no response before closing:

import { request, METHODS } from 'http';

  const options = {
    host: 'api.urbandictionary.com',
    path: '/v0/define/?term=wat',
    pathname: '/v0/define/',
    search: 'term=wat',
    method: 'GET',
    headers: { Accept: 'application/json' }
  }

  const req = request(options, (res) => {
    let resAccum = '';
    res.on('data', (chunk) => {
      console.log('GOT chunk', chunk);
      resAccum  = chunk;
    });
    res.on('close', () => console.log('FINISHED', resAccum)); // FINISHED
    res.on('error', err => console.log(err));
  });

  req.on('error', err => console.log(err));
  req.end();

CodePudding user response:

I found three problems:

  1. You need to be listening to the end event, not the close event
  2. You need to be using https
  3. Your path was incorrect. It won't accept a / before the ?.

The close event occurs on the req object, not the res object.

Code example here in the doc. I would agree that the wording in the doc does not make this clear, but there are multiple coding examples in the doc that show using res.on('end', ...) to know when all of the response has arrived.

Here's a working version that also parses the JSON:

import { request } from 'https';

const options = {
    host: 'api.urbandictionary.com',
    path: '/v0/define?term=wat',
    method: 'GET',
    headers: { Accept: 'application/json' }
}

const req = request(options, (res) => {
    console.log(res.headers);
    console.log(res.statusCode, res.statusMessage);

    let resAccum = '';
    res.on('data', chunk => {
        resAccum  = chunk.toString();
    });

    // *** Use end event here ***
    res.on('end', () => {
        console.log('FINISHED');
        const data = JSON.parse(resAccum);
        console.log(data);
    });
    res.on('error', err => console.log(err));
});

req.on('error', err => console.log(err));
req.end();

FYI, the libraries listed here are higher level than the http.request() library and are simpler to use for coding like this and very well tested. I highly recommend picking your favorite from that list. I personally use got() because I like how they've designed the interface, but any in that previous list are good choices.

For reference, the same result can be achieved with this using the got() library:

import got from 'got';

got("https://api.urbandictionary.com/v0/define?term=wat").json().then(result => {
    console.log(result);
}).catch(err => {
    console.log(err);
});
  • Related