【问题标题】:reading REST POST response node.js阅读 REST POST 响应 node.js
【发布时间】:2017-09-11 05:06:27
【问题描述】:

我可以在 rest 客户端中测试一个 post call,它显示标题为:

Cache-Control: no-cache, no-store, must-revalidate
Connection: keep-alive
Content-Encoding: gzip
Content-Language: en
Content-Length: 49
Content-Type: application/json
Date: Fri, 14 Apr 2017 21:05:42 GMT

我调用帖子的代码如下:

var https = require('https');
... var jsonObject = JSON.stringify({
            "Name" : optyName
        });

        // prepare the header
        var postheaders = {
            'Content-Type' : 'application/vnd.oracle.adf.resourceitem+json',
            'authorization' : 'Basic am9obi5kdW5iYXI6dnBoODk1ODM=',
            gzip: true
        };

        // the post options
        var optionspost = {
            host : 'myhost',
            port : 443,
            path : '/salesApi/resources/11.1.11/opportunities?fields=OptyId&onlyData=true',
            method : 'POST',
            headers : postheaders,
        };

        // do the POST call
        var reqPost = https.request(optionspost, function(error,response,body) {
             console.log('the decoded data is: ' + body)
         });

  reqPost.write(jsonObject);
        reqPost.end();
}

但是我得到了打印的东西:

the decoded data is: undefined

【问题讨论】:

    标签: javascript node.js rest https http-post


    【解决方案1】:

    var http = require("http"), zlib = 要求("zlib");

    函数 getGzipped(url, 回调) { // 存储流解压的缓冲区 变量缓冲区 = [];

    http.get(url, function(res) {
        // pipe the response into the gunzip to decompress
        var gunzip = zlib.createGunzip();            
        res.pipe(gunzip);
    
        gunzip.on('data', function(data) {
            // decompression chunk ready, add it to the buffer
            buffer.push(data.toString())
    
        }).on("end", function() {
            // response and decompression complete, join the buffer and return
            callback(null, buffer.join("")); 
    
        }).on("error", function(e) {
            callback(e);
        })
    }).on('error', function(e) {
        callback(e)
    });
    

    }

    getGzipped(url, function(err, data) { 控制台.log(数据); });

    【讨论】:

      【解决方案2】:

      您在代码中打印响应正文,而不是响应标头。

      尝试此代码以查看标题:

      var reqPost = https.request(optionspost, function(error,response,body) {
          console.log('response headers: ' + response.getHeaders())
      });
      

      https://nodejs.org/api/http.html#http_response_getheaders

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-09
        • 2022-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-28
        • 1970-01-01
        相关资源
        最近更新 更多