【发布时间】:2018-04-29 06:18:45
【问题描述】:
我正在 Node.js 中开发一个 RESTful 应用程序,并且我正在使用 https 库实现 http 请求。
目前,每个文件都包含一个带有某些参数的 http 请求,如下面的代码所示:
//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();
}
现在我想将 http 请求本身封装在一个单独的文件中(出于重构目的),以便每个文件都会调用模板并将其自己的参数传递给它。但这就是问题所在。是否可以将参数传递给回调?
//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();
}
我会在另一个文件中定义并传递函数的参数
//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);
})
但这显然行不通。你有什么建议可以给我吗?提前致谢。
【问题讨论】:
标签: javascript node.js asynchronous callback