【问题标题】:how to receive gzip data ? Node.js如何接收 gzip 数据?节点.js
【发布时间】:2021-07-28 13:29:19
【问题描述】:

我正在尝试从 KEEPA 检索有关亚马逊产品的数据。

我正在努力以正确的 JSON 格式接收数据,因为 KEEPA 以 gzip 格式发送数据。

我尝试使用“decompressResponse”模块来帮助获取 JSON 格式的数据,但每次调用都会收到多次。

由于代码如下所示,我的控制台收到了一大堆乱码。 让我知道我在这里缺少什么,或者如果您有更好的建议,请告诉我。 谢谢

const express = require("express");
const https = require("https");
const bodyParser = require("body-parser");


const app = express();

app.use(bodyParser.urlencoded({extended: true}));

app.get("/", function(req, res) {

res.sendFile(__dirname + "/index.html");
});

app.post("/", function(req, res) {


const query = req.body.asinId;
const apiKey = "MY_API_KEY";
const url = "https://api.keepa.com/product?key=" + apiKey + "&domain=1&asin=" + query;

const options = {
methode: "GET",
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Accept-Encoding":"gzip"
  }
 }

https.get(url,options,function(res) {
console.log(res.statusCode);
console.log(res.headers);
var data;

res.on("data", function(chunk){
if(data){
data = chunk;
} else {
data += chunk;
}

console.log(data);
});
});

res.send("server is running");

});


 app.listen(3000, function() {
 console.log("server is running on port 3000");
});

【问题讨论】:

    标签: node.js get gzip


    【解决方案1】:

    您是否尝试过将内置的zlib 模块与gunzip() 一起使用?

    zlib.gunzip(data, (error, buff) => {
      if (error != null) {                                       
          // An error occured while unzipping the .gz file.
      } else {                                                    
        // Use the buff which contains the unzipped JSON.
    
        console.log(buff)
      }
    });
    

    您的代码的完整示例:https://www.napkin.io/n/7c6bc48d989b4727

    【讨论】:

    • 感谢您的回答 Thomas,很遗憾,我仍然收到上面示例的乱码。
    【解决方案2】:

    输出函数错了..下面是正确的

    https.get(url,options,function(response) {
    response = decompressResponse(response);
    console.log(res.statusCode);
    console.log(res.headers);
    let data = '';
    
    response.on("data", function(chunk){
    data += chunk;
    });
    
    response.on("end",function(){
    console.log(data);
    });
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-16
      • 1970-01-01
      相关资源
      最近更新 更多