javascript - 在 Node.JS 中向 http.get 传递参数

标签 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);
}

function callbackFunc(res, myParameter){}

最佳答案

创建一个返回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);
    });
}

或者您可以使用Function.bind()根据Peter Lyons的建议。第二个和后续参数将在调用时间参数之前传递给回调。

关于javascript - 在 Node.JS 中向 http.get 传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31589288/

相关文章:

javascript - 在 svg 中添加图像

javascript - 使用嵌套 HTML 元素处理拖放?

javascript - 带有默认文本的文本框

http - 我无法从 curl 命令返回 get 200 响应

http - 为 GET 请求设置的正确 Content-Length 是多少?

javascript - 如何处理 CORS 错误代码?

javascript - 单向滚动 : horizontal OR vertical

node.js - 如何在 IIS 上正确设置 ReactJS 应用程序?

node.js - 无法将异步函数部署到 Google Cloud Functions

node.js - 在 Q 中记录所有拒绝的 promise