0

I'm using xmlhttprequest to post, and get the response content gzipped (deliberately). I tried to decompress it using zlib, but it seems to work only with a response object, other nodejs modules were unhelpful too. Are there other simple ways to do that?

Here is my code:

function doPost(url, body, onSuccess) {
    var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
    var httpReq = new XMLHttpRequest();
    httpReq.open('POST', url, true);
    httpReq.setRequestHeader('Content-Type', 'application/json');
    httpReq.setDisableHeaderCheck(true)
    httpReq.setRequestHeader('Accept-Encoding', 'gzip');
    httpReq.onreadystatechange = function () {
        if (httpReq.readyState == 4 && httpReq.status == 200) {
            if (httpReq.responseText.Error == undefined) {
                if (typeof onSuccess === 'function') {
                    // unzip here...
                    onSuccess(JSON.parse(httpReq.responseText)); 
                }
            } else {
                throw 'error in dopost: ' + httpReq.responseText.Error;
            }
        }
    }
    httpReq.send(JSON.stringify(body));
}
4

1 回答 1

-1

看看这个答案。

它使用request模块,比 XMLHttpRequest 更好、更容易使用。

于 2013-07-14T21:50:14.267 回答