How to get data out of a Node.js http get request

后端 未结 7 1223
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 23:25

I\'m trying to get my function to return the http get request, however, whatever I do it seems to get lost in the ?scope?. I\'m quit new to Node.js so any help would be appr

7条回答
  •  Happy的楠姐
    2020-11-28 23:36

    Simple Working Example of Http request using node.

    const http = require('https')
    
    httprequest().then((data) => {
            const response = {
                statusCode: 200,
                body: JSON.stringify(data),
            };
        return response;
    });
    function httprequest() {
         return new Promise((resolve, reject) => {
            const options = {
                host: 'jsonplaceholder.typicode.com',
                path: '/todos',
                port: 443,
                method: 'GET'
            };
            const req = http.request(options, (res) => {
              if (res.statusCode < 200 || res.statusCode >= 300) {
                    return reject(new Error('statusCode=' + res.statusCode));
                }
                var body = [];
                res.on('data', function(chunk) {
                    body.push(chunk);
                });
                res.on('end', function() {
                    try {
                        body = JSON.parse(Buffer.concat(body).toString());
                    } catch(e) {
                        reject(e);
                    }
                    resolve(body);
                });
            });
            req.on('error', (e) => {
              reject(e.message);
            });
            // send the request
           req.end();
        });
    }
    

提交回复
热议问题