NodeJs,Https POST没有响应

时间:2018-07-30 13:11:05

标签: node.js firebase https request google-cloud-functions

我试图通过执行以下代码,使用nodeJS模块 https 发布https请求:

 cors(req, res, () => {
    let data = {
      "password": "passwordhere",
      "receipt-data": req.body.receiptData
    };

    let headers = { 'Content-Type': 'application/json' };
    let options = {
      hostname: 'sandbox.itunes.apple.com',
      method: 'POST',
      path: '/verifyReceipt',
      headers: headers,
      port: 443
    }

    let httpsRequest = https.request(options,function(res){
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.on('data',function(chuck){
          responseDate+=chuck;
        });
    }) ;

    let responseDate = '';


    httpsRequest.on('error',function(e){
      console.log("inside the error");
      console.log(e);
    });

    httpsRequest.on('end',function(){
      console.log("inside the end");
      JSON.parse(responseDate)
      res.send({res:JSON.parse(responseDate)});
    });

    httpsRequest.write(JSON.stringify(data));
    httpsRequest.end();

      });
    });

结果:

enter image description here

因此发生了请求时间,并且未执行httpsRequest.on错误/结束!

有谁能提供我的错在哪里?

谢谢。

1 个答案:

答案 0 :(得分:1)

您要使用res.on('end', ...),而不是httpsRequest.on('end', ...)。请参见the doc中的示例。

let httpsRequest = https.request(options,function(res){
    let responseDate = '';
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.on('data',function(chuck){
      responseDate+=chuck;
    });
    res.on('end', function() {
        console.log("inside the end");
        // may have to url decode data here before you have the JSON that was sent
        res.send({res:responseDate});            
    });
});

httpsRequest.on('error', function(e) {
    res.status(500).send("error occurred")
});
// write data to request body
httpsRequest.write(postData);
httpsRequest.end();

但是,更好的是,我建议您只使用requestrequest-promise模块来为您完成所有这些工作。

const rp = require('request-promise');

rp(options).then(function(data) {
    res.json(data);
}).catch(err => {
    // handle error here
    console.log(err);
    res.status(500).send("error occurred")
});