Home > Enterprise >  How to get the data from res.on in Nodejs
How to get the data from res.on in Nodejs

Time:05-08

I use the GET method to request api,but now I want to return chunk as the value of that method. How I can write to get the global 'chunk' value?

res.on('data', (chunk) => {
            console.log('body:${chunk}`);
        
        })

CodePudding user response:

If you mean how to get the chunks on client-side, I suggest to use axios and configure the option onDownloadProgress, which allows handling of progress events for downloads.

Please, bear in mind that it only works for browsers, if you intend to work with other clients (e.g. API), that will not work.

CodePudding user response:

This is my function, I want to return the chunk that includes the WeChat minapp user's openid information, and I can use the openid to judge if the user has register or use the openid to get more information.

function getWXOpenId(body) {

    //bode:minapp post value;
    //console.log(body);
    var params = new URLSearchParams(body);
    //https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code
    var wx_appid = '';
    var wx_secret = '';
    var wx_tempCode = params.get("code");
    var wx_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='   wx_appid   '&secret='   wx_secret   '&js_code='   wx_tempCode   '&grant_type=authorization_code';
    var req = https.request(wx_url, function (res) {
        console.log('statusCode'   res.statusCode);
        res.setEncoding('utf8');
        res.on('data', (chunk) => {
             //the chunk has the openid value
            console.log(`body: ${chunk}`);

        })
        res.on('end', () => {
            console.log('end');
        });
    });
    req.on('error', (e) => {
        console.error('error'   e.message);
        return ;
    });
    //end
    req.end();
}

Now I want return the trunk value to get the openid.

  • Related