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.
It seems that you want to pass the options as an additional argument after the callback, not expect it to be passed within the callback.
Instead of:
test.httpResponse(function(response, options) {
// ^ you don't want option to be part of the callback
console.log('response = ' + response);
})
You want:
test.httpResponse(function(response) {
console.log('response = ' + response);
}, options)
// ^ pass options as second parameter
As Bergi mentioned below, the usual convention in Node is to pass the callback as the last parameter (as you can see in the https.request method you're using), which would require you to flip the arguments of your httpResponse method:
module.exports.httpResponse = function (options, callback) {
// ... ^^^^^^^^^^^^^^^^^ flip these two so that callback is at the end
}
Then use it:
test.httpResponse(options, function(response) {
// ^ pass options as first parameter
console.log('response = ' + response);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With