JSFiddle - React, Tailwind, and code Playground
JavaScript
'use strict';
var URL = require('url');
var querystring = require('querystring');
var Q = require('q');
var https = require('https');
/**
* Wraps HTTPS module from nodejs with Promise
* @module common/http_request
*/
var createRequestSetting = function (host, path, data, cookies) {
return {
method: 'POST',
port:443,
host: host,
path: path,
headers: {
Accept: 'application/json, text/javascript, */*; q=0.01',
'Content-Type':
'application/x-www-form-urlencoded; charset=UTF-8',
'Content-Length': Buffer.byteLength(data),
'Cookie': cookies,
},
rejectUnauthorized: false,
};
};
var httpRequest = {};
/**
* Cookie string in a format of "[KEY]=[VALUE]"
* @typedef {string} Cookie
*/
/**
* Send a POST request to URL with payload
* @param {string} url - URL
* @param {?Object} payload - Form request data in key-value pairs format
* @param {Cookie[]} cookies - Array of cookies going to be attach
* @return {Promise<string>} - Reply from the router
* @alias module:common/http_request#post
*/
httpRequest.post = function (url, payload, cookies) {
var urlObj = URL.parse(url);
var data = payload ? querystring.stringify(payload) : '';
var setting = createRequestSetting(urlObj.host, urlObj.path, data, cookies);
// Create request object
var cache = [];
var deferred = Q.defer();
var req = https.request(setting, function (res) {
// Wraps http request in a promise object
res.setEncoding('utf8');
// Get JSON response
res.on('data', function (chunk) {
cache.push(chunk);
});
res.on('end', function () {
deferred.resolve(cache.join(''));
});
// Catch error from HTTPS request
res.on('error', function (err) {
deferred.reject(err);
});
});
// Catch error from HTTPS request
req.on('error',...