2017-05-29 137 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(); 

       }); 

     };