I'm developing a RESTful application in Node.js and I'm implementing the http requests using the https library.
At the moment, each file contains an http request with certain parameters as you can see in the code below:
//test.js
var https = require('https');
module.exports.httpResponse = function (callback) {
var options = {
host: 'api.github.com',
path: '/users/Guilherme-Routar',
method: 'GET',
//headers: {'user-agent': userAgent}
}
var str = '';
var request = https.request(options, function (response) {
response.on('data', function (body) {
str += body;
});
response.on('end', function () {
return callback(str);
});
});
request.on('error', (e) => {
console.log(e);
});
request.end();
}
Now I want to encapsulate the http request itself in a separated file (for refactoring purposes) so that each file will call the template and pass it's own parameters to it. But here's where the issue lies. Is it possible to pass parameters to a callback?
//test.js
var https = require('https');
//I tried adding 'options' next to the 'callback' parameter
module.exports.httpResponse = function (callback, options) {
var str = '';
var request = https.request(options, function (response) {
response.on('data', function (body) {
str += body;
});
response.on('end', function () {
return callback(str);
});
});
request.on('error', (e) => {
console.log(e);
});
request.end();
}
On another file I'd define and pass the parameters of the function
//user.js
var test = require('../test.js');
var options = {
host: 'api.github.com',
path: '/users/Guilherme-Routar',
method: 'GET',
//headers: {'user-agent': userAgent}
}
// Passing 'options' as a parameter
test.httpResponse(function(response, options) {
console.log('response = ' + response);
})
But this clearly doesn't work. Any suggestions you can give me? Thanks in advance.