簡體   English   中英

Node.js消耗來自外部API的deflate響應

[英]Nodejs consume deflate response from external API

這應該是一個簡單的問題,但是為了我的生活,我無法使其正常運行,我正在使用這樣的Web服務:

var XMLHttpRequest = require('XMLHttpRequest').XMLHttpRequest;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://rest.gestionix.com/api/v2/products? 
branch_id=7471&filter=0119080PMDSV&results_per_page=5&page=1&fields=id');
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.onreadystatechange = function(event) {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            console.log(xhr.responseText);
        }
    }
    console.log(xhr.getAllResponseHeaders());
};
xhr.setRequestHeader('Accept','application/json');
xhr.setRequestHeader('Accept-Encoding','decode');
xhr.setRequestHeader('Content-Encoding','decode');
xhr.setRequestHeader('Encoding','decode');
xhr.setRequestHeader('apikey', '---'); <<< of course I'm using an apikey
xhr.send();

api返回此標頭:

cache-control: max-age=60
content-length: 22766
content-type: application/json
content-encoding: deflate
server: Microsoft-IIS/10.0
x-aspnet-version: 4.0.30319
x-powered-by: ASP.NET
date: Mon, 02 Jul 2018 16:31:32 GMT
connection: close

但是,內容只是一堆奇怪的字符:

a^G4Wk wC p Ȳ G FZ} Bo W i gu$H ^; ,Wf 촞 } : %6,e1D ml 7UO DzK m } t。 dS7 Q >5 y I.;E PH } / X W{ XXSP v。[ k W׈ P { W >Z י R ׺4T ]X m< Ns'՟ f 0X:V.W C ҁ P #d T gb yIn c-+EP #= | V f 9 Ղ h .: r yF ر !σr L/E d7 7\\\\ +ɠ N 3 a {{- )。〜 \\s ^5 qq.t oP - ;( 4 o6

我嘗試使用不同的編碼,但是結果總是相同的,我一直在尋找有關如何解壓縮的文檔,但是我找不到任何有效的方法,如果有人有可以指向我正確方向的鏈接,我會真正欣賞它。

服務器可能會忽略您對非壓縮數據的請求,並向您發送壓縮數據。 content-encoding標頭中所述,它使用deflate算法。 您可以自己放氣。 nodejs具有本機庫zlib,可以壓縮數據。

var zlib = require("zlib")

// in response callback
zlib.deflate(xhr.response, function (error, result) {
    console.log(result.toString());
});

就我而言,我無法讀取XMLHttpRequest數據,因為該庫無法處理二進制數據,而是將所有數據作為字符串處理。 這是有問題的,因為轉換一些二進制字符(如0)會破壞數據。 我必須切換到請求庫。 我用來測試的代碼是

var zlib = require("zlib")
var request = require("request")

request('http://something...', { encoding: null }, function (error, response, body) {
    zlib.deflate(xhr.response, function (error, result) {
        console.log(result.toString());
    });
});

好吧,我不想讓這個問題無解,以防萬一其他人需要它。 首先,您需要此樣板代碼

/ **鍋爐板代碼*處理響應。 * @param {Object}標頭*響應標頭名稱-值對的哈希。 * @param {String}主體*未壓縮的響應主體。 * / function processResponse(headers,body){

  **do something with the response**

    } else {
        console.log("Response is empty.");
    }
}

/**
 * Manage an error response.
 *
 * @param {Error} error
 *   An error instance.
 */
function handleError(error) {
    // Error handling code goes here.
    console.log("Error Found: " + error);

}

/**
 * Obtain the encoding for the content given the headers.
 *
 * @param {Object} headers
 *   A hash of response header name-value pairs.
 * @return {String}
 *   The encoding if specified, or 'utf-8'.
 */
console.log('------------ Getting Charset  ------------');
function obtainCharset(headers) {
    // Find the charset, if specified.
    var charset;
    var contentType = headers['content-type'] || '';
    var matches = contentType.match(/charset=([^;,\r\n]+)/i);
    if (matches && matches[1]) {
        charset = matches[1];
    }
    console.log('------------ Charset is ' + charset + ' (utf-8 if null)  ------------');
    return charset || 'utf-8';
}

此功能將負責處理,它們位於頂部。

然后您需要運行您的請求,就我而言,我使用的是普通的var request = require('request-promise');

var req = request({url: yoururlhere *,headers:** yourheadershere },function wait(error,response){if(error){return handleError(error);} else if(response.statusCode> = 400){返回handleError(new Error(util.format('Response with status code%s。',response.statusCode)));} console.log('-----------解壓縮響應----- ------'); zlib.inflateRaw(Buffer.concat(buffers),function(gunzipError,bodyBuffer){if(gunzipError){return handleError(gunzipError);} var charset = getCharset(response.headers); processResponse (response.headers,bodyBuffer.toString(charset));});}); req.on('data',function(buf){buffers [buffers.length] = buf;});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM