2017-05-29 135 views
-1

我在我的配置节点中使用节点请求var request = require(“request”);来执行POST请求,并在响应中获取需要在所有其余请求中引用的Cookie。使用cookie请求请求内的节点

我试着启用COOKIE JAR,如果我在第一个请求下链接我的请求,但我想从自定义节点调用GetList之类的请求的其余部分,可以正常工作。

我尝试toughcookie(文件cookie)不工作,当我添加var j = request.jar(new FileCookieStore(‘cookies.json’)); 节点停止工作,没有错误。

下面是我的配置节点,使用我得到Cookie的代码。

function myAuthNode(n) { 

     RED.nodes.createNode(this,n); 
     this.username=n.username; 
     this.password=n.password; 


      this.connect=function(){ 
       //TODO-NG need to make URL configurable 
       request.post({url: "http://localhost:8080/api/method/login", qs: {usr: this.username, pwd: this.password}}, function(err, res, body) { 

        if(err) { 
          return console.error(err); 
        } 

        console.log("HERE IF I PUT REQUEST Works fine"); 
        console.log("CAN WE PASS ANOTHER REQUEST here from calling SOURCE to execute here?"); 

       }); 

     }; 



    } 

在这里,在这个自定义节点我打电话

// The main node definition - most things happen in here 
    function GetListNode(n) { 
     // Create a RED node 
     RED.nodes.createNode(this,n); 
     console.log('I am called'); 

     //using auth config now you are connected, tell me what is needed? 
     this.authConfig=RED.nodes.getNode(n.auth); 
     //connect to config and do auth 

     this.authConfig.connect(); 

//THIS ALWAYS FAILS due to cookie not found where as I enable request JAR 

     request.get({url: "http://localhost:8080/api/resource/Project"}, function(err, res, body) { 

       if(err) { 
         return console.error(err); 
       } 

        console.log("Response body:", body); 

      }); 


    } 

请建议如何处理cookie的请求中,让所有的请求后,身份验证工作正常?

我们可以将请求定义传递给另一个要执行的请求吗或Cookie如何处理?

+2

创建单个cookie jar实例并传递它或设置为默认值:var j = request.jar(); var request = request.defaults({jar:j})'。你也可以尝试打印出cookie jar的内容,'j.getCookieString(url);' –

+0

感谢您的建议Risto。我早些时候在myAuthNode中试过,它向我展示了我的cookie,但是如何在GetListNode中使用它,同时执行另一个请求,该请求也是相同的请求对象,其中我设置了默认值,但它从来没有读过那个jar,我做错了什么? –

+0

您是否可以在服务器端验证请求是否没有发送任何cookie标头,只是'console.log'或拦截代理请求来查看标头。 –

回答

0

我解决了这个由内部GetListNode()下面做时,我转移呼叫内第二请求:

this.authConfig.connect(function(){request.get({url: "http://localhost:8080/api/resource/Project"}, function(err, res, body) { 

     if(err) { 
       return console.error(err); 
     } 

      console.log("Response body:", body); 

    });}); 

和配置节点内我没有下面,增加了一个函数参数和调用该传递函数,工作得很好:):

this.connect=function(f){ 
       //TODO-NG need to make URL configurable 
       request.post({url: "http://localhost:8080/api/method/login", qs: {usr: this.username, pwd: this.password}}, function(err, res, body) { 

        if(err) { 
          return console.error(err); 
        } 

        f.call(); 

       }); 

     };