NodeJS native http/https json POST request

0
// Load http/https module depending on API protocol (see .env file)
var httpRequest = process.env.BACKEND_API_PROTOCOL === 'https' ? require('https') : require('http');

const httpData = JSON.stringify({
    'email': req.body.email,
    'password': req.body.password
})

const httpOptions = {
    'host': process.env.BACKEND_API_HOST,
    'port': process.env.BACKEND_API_PORT,
    'path': process.env.BACKEND_API_PATH + '/auth',
    'method': 'POST',
    'headers': {
        'Content-Type': 'application/json',
        'Content-Length': httpData.length
    },
    timeout: 30000
}

var request = httpRequest.request(httpOptions, function(response) {

    debug('statusCode: ' + response.statusCode);
    debug('headers', response.headers);

    response.setEncoding('utf8');
    var body = ''
    response.on('data', function(chunk) {
        body += chunk;
    });
    response.on('end', function() {
        
        
        
        res.jsonp(JSON.parse(body));
    })
});

request.on('error', function(err) {
    res.jsonp(err)
});

request.write(httpData);
request.end();
Share.

About Author

Christian Unnerstall

Christian Unnerstall, founder of devshooin.com, enjoys designing and building things that look nice and work well, whether it's websites or services within the interwebs. Have questions - feel free to reach out to him. Enjoy

Leave a Reply