我是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);
?我還可以如何設置一個屬性發送給控制器?
嘗試從代碼中刪除end()。 – KlwntSingh
@ user111111111如果我刪除,則拋出: '''events.js:85 throw er; //未處理'錯誤'事件 ^ 錯誤:套接字掛斷 ''' –