javascript - How to get Node.js response headers and status code? - Stack Overflow

I don't have a lot of experience with Node.js, but it seems the httphttps documentation is pretty

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 mon 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);
  }
);

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 mon 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);
  }
);
Share Improve this question asked Nov 7, 2018 at 21:41 neaumusicneaumusic 10.5k11 gold badges59 silver badges86 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

In your code here:

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

You get a response object. That object is an instance of http.IningMessage 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.

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 pletes 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'));

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744182201a4562033.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信