繁体   English   中英

如何获取 Node.js 响应头和状态码?

[英]How to get Node.js response headers and status code?

我对 Node.js 没有太多经验,但似乎 http/https 文档非常糟糕,我无法弄清楚如何获取常见的响应头:

  • 缓存控制
  • 编译指示
  • 过期
  • 内容类型
  • 内容长度
  • 日期
  • 联系
  • 设置 Cookie
  • 严格的运输安全

鉴于我下面的代码,我如何确定 statusCode 和响应标头?

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

在您的代码中:

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

你得到一个响应对象。 该对象是http.IncomingMessage一个实例,它可以像这样访问response.statusCoderesponse.headers

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

许多人(包括我自己)发现更高级别的requestrequest-promise模块更易于使用。 它们建立在http.requesthttps.request ,但为您提供了一个更易于使用的界面。

我正在寻找同样的东西。 使用这里和其他来源的一些示例,我有一个工作 node.js 示例要分享。

  1. 创建一个 node.js 项目
  2. 创建一个 index.js 文件并将下面的代码放入其中。
  3. 从您的项目文件夹中运行:node index.js

索引.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'));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM