6

I don't have a lot of experience with Node.js, but it seems the http/https documentation is pretty awful, and I can't figure out how to get common response headers:

  • Cache-Control
  • Pragma
  • Expires
  • Content-Type
  • Content-Length
  • Date
  • Connection
  • Set-Cookie
  • Strict-Transport-Security

Given my code below, how can I determine the statusCode and response headers?

const promiseResponse = new Promise((resolve, reject) => {
  const fullResponse = {
    status: '',
    body: '',
    headers: ''
  };

  const request = https.request({
    hostname: testHostname,
    path: testPath,
    method: testMethod,
    headers: {
      'x-jwt': jwt,
      'content-type': contentType,
    }
  });

  request.on('error', reject);
  request.on('response', response => {
    response.setEncoding('utf8');
    response.on('data', chunk => { fullResponse.body += chunk; });
    response.on('end', () => {
      fullResponse.body = JSON.parse(fullResponse.body);
      resolve(fullResponse);
    });
  });

  request.write(JSON.stringify(testBody));
  request.end();
});

promiseResponse.then(
  response => {
    console.log('success:', response);
  },
  error => {
    console.error('error:', error);
  }
);

2 Answers 2

3

In your code here:

request.on('response', response => { ... });

You get a response object. That object is an instance of http.IncomingMessage which can access the response.statusCode and response.headers like this:

request.on('response', response => {
    console.log(response.statusCode);        
    console.log(response.headers);
    response.on('data', chunk => { fullResponse.body += chunk; });
});

Many people (myself included) find the higher level request or request-promise modules to be much, much easier to use. They are built on top of http.request and https.request, but give you a much easier to use interface.

Sign up to request clarification or add additional context in comments.

Comments

0

I was looking for the same thing. Using some examples from here and other sources I have a working node.js sample to share.

  1. Make a node.js project
  2. Create a index.js file and put the code below into it.
  3. From inside your project folder run: node index.js

index.js:

// dependencies
const express = require('express');
const https = require('https');
var Promise = require('es6-promise').Promise;
const { stringify } = require('querystring');

const app = express();

// from top level path e.g. localhost:3000, this response will be sent
app.get('/', (request, response) => {

  
    getHeaderAndDataResponse(function (res) {
        console.log('getHeaderAndDataResponse returned');
        response.send(res);
    });

});


/**
 * get all headers and data.
 * date is returned to the caller
 * headers ar output to console for this example.
 * @param {*} callback 
 */
function getHeaderAndDataResponse(callback) {

    console.log('Entering getHeaderAndDataResponse');

    // surround the https call with a Promise so that
    // the https ansyc call completes before returning.
    // Note: may need to change date to today.
    let retVal = new Promise(function (success, fail) {
        https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&start_date=2020-07-22',
            function (resp) {

                let data = '';

                console.log("Got response: " + resp.statusCode);

                // quick dirty way to format the headers
                // output to console, but could easily be added
                // to the JSON returned below. 
                for (var item in resp.headers) {
                    let h = '"' + item + '": ' + '"' + resp.headers[item] + '"';
                    console.log(h);
                }

            // A chunk of data has been recieved.
            resp.on('data', (chunk) => {
                data += chunk;
            });

            // The whole response has been received. Print out the result.
            resp.on('end', () => {

                let exp = JSON.parse(JSON.stringify(data));

                console.log('got data');

                success(exp);

            });


            }).on('error', (err) => {
                console.log("Error: " + err.message);
                fail(err.message);

            })
    }).then(retVal => {
        console.log('got then');
        return callback(retVal);
    });

}

// set the server to listen on port 3000
app.listen(3000, () => console.log('Listening on port 3000'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.