Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将参数传递到Node.JS中的http.get_Javascript_Node.js_Http - Fatal编程技术网

Javascript 将参数传递到Node.JS中的http.get

Javascript 将参数传递到Node.JS中的http.get,javascript,node.js,http,Javascript,Node.js,Http,我正在执行http或https get请求(取决于url),我想向http或https get请求传递相同的回调函数。 我的问题是,我还想向回调函数传递另一个参数。 我怎么做 例如,如何将myParameter传递给回调函数 var myParameter = 1 if(url.indexOf('https') === 0 ) { https.get(url, callbackFunc); else{ http.get(url, callbackFunc); } functio

我正在执行http或https get请求(取决于url),我想向http或https get请求传递相同的回调函数。
我的问题是,我还想向回调函数传递另一个参数。
我怎么做

例如,如何将myParameter传递给回调函数

var myParameter = 1
if(url.indexOf('https') === 0 ) {
    https.get(url, callbackFunc);
else{
    http.get(url, callbackFunc);
}

function callbackFunc(res, myParameter){}

首先,将callbackFunc的参数顺序更改为

function callbackFunc(myParameter, res) {

}
(首先是myParameter,以便我们可以按如下所示绑定它,然后是res)

然后你可以做:

var boundCallback = callbackFunc.bind(null, myParameter);

然后在调用http或https get时使用
boundCallback
而不是
callbackFunc

创建一个返回
callbackFunction
的函数,将自定义参数存储在闭包中

function createCallback(myParam) {
    return function(res) {
           console.log(res, myParam);
    }
}

var myParameter = 1
if(url.indexOf('https') === 0 ) {
    https.get(url, createCallback(myParameter));
else{
    http.get(url, createCallback(myParameter2));
}
你也可以使用一个额外的匿名函数

var myParameter = 1
if(url.indexOf('https') === 0 ) {
    https.get(url, function(res){
       myCallback(res, param1);
    });
else{
    http.get(url,  function(res){
       myCallback(res, param2);
    });
}

或者,您可以按照建议使用。第二个参数和后续参数将在调用时参数之前传递给回调函数。

谢谢,它可以工作!错误不是第二个,而是res