2015-07-13 35 views
1

我是Sails.js的新手,我試圖製作一個過濾器來使用來自更高服務器的承載令牌進行授權,該守護者響應OAuth2身份驗證來自GitHub API。服務流效果良好。我已經意識到了Passport.js,但我試圖自己實現這一點。我想出了一個policy看起來像:SailsJS - Nodejs Https-Request。發送後無法設置標題

module.exports = function (req, res, next) { 
    var httpsExec = require('https'); 
    if (req.headers.authorization) { 
    var parts = req.headers.authorization.split(' '); 
    if (parts.length == 2) { 
     var tokenType = parts[0] 
     , credentials = parts[1]; 
     if (/^Bearer$/i.test(tokenType) || /^bearer$/i.test(tokenType)) { 
     httpsExec.request({ 
      host: 'api.github.com', 
      post: 443, 
      path: '/user', 
      method: 'GET', 
      headers: {'Authorization': 'token ' + credentials, 'User-Agent': 'curly'} 
     }, function (response) { 
      var responseData = ''; 
      response.setEncoding('utf8'); 

      response.on('data', function (chunk) { 
      responseData += chunk; 
      }); 

      response.once('error', function (err) { 
       next(err); 
      }); 

      response.on('end', function() { 
      try { 
       req.options.user = JSON.parse(responseData); 
       next(); 
      } catch (e) { 
       res.send(401, {error: e}); 
      } 
      }); 
     }).end(); 
     } else { 
     console.err("The token is not a Bearer"); 
     res.send(401) 
     } 
    } 
    } else { 
    res.send(401, {error: "Full authentication is necessary to access this resource"}) 
    } 

}; 

政策被調用一次我打了控制器的路線,但它拋出一個_http_outgoing.js:335 throw new Error('Can\'t set headers after they are sent.'); ^ Error: Can't set headers after they are sent.

且工藝終止。

我認爲這個問題是next()returns我想無論我想,把next()電話,但還是給了我這個錯誤,如果我刪除然後我鎖定策略的要求。

編輯

我沒有,我只是設置一些屬性上req.options.values和發生同樣的問題,政策的一個簡單的示例,所以也許可能是一個問題與req.options.requestData = JSON.parse(responseData);?我還可以如何設置一個屬性發送給控制器?

+0

嘗試從代碼中刪除end()。 – KlwntSingh

+0

@ user111111111如果我刪除,則拋出: '''events.js:85 throw er; //未處理'錯誤'事件 ^ 錯誤:套接字掛斷 ''' –

回答

1
  response.once('error', function (err) { 
       next(err); 
      }); 

      response.on('end', function() { 
      try { 
       req.options.user = JSON.parse(responseData); 
       next(); 
      } catch (e) { 
       res.send(401, {error: e}); 
      } 
      }); 

兩者都正在執行。檢查console.log(「something」)是否有錯誤,以查看是否有錯誤。

+0

請接受答案 – KlwntSingh

1

當您嘗試一起修改請求和響應或將其中一個修改爲兩次時,會發生這種情況。

在你的代碼中,我認爲回調被調用了兩次,同時你也在修改響應。檢查你正在調用callback「next()」的行。你會發現你的問題。

+0

我在控制器上發現問題,而不是在策略上,因爲我調用回調'next() '是在if/else或try/catch方法上進行控制器方法的開始這些行 'var artifact = req.body.artifact;' 'if(!artifact)res.badRequest({error:「 「});' 當工件不在主體上,並且必須返回錯誤的請求,但有時它會崩潰到異常 –

+0

給** req.param(」key「)**一槍。 所以,如果你想獲得神器,然後嘗試** req.param( 「神器」)**和使用它像這樣 如果(req.param( 「神器」)){} –

相關問題