2016-10-26 3 views
0

Как новичок NodeJS, я открываю для себя новые вещи об этой структуре, очень интересные.Firebase: Неизвестная ошибка сервера

Так что я пытался написать сценарий NodeJS которые сообщаются с базой данных FireBase, но эта ошибка была пойманной

Есть ли у Вас идеи о этой ошибке, пожалуйста?

authLinkedIn>node bin\www 
Listening on port 3000 
[Simple Login] Login Failed! { Error: An unknown server error occurred. 
    at Error (native) 
    at T (authLinkedIn\node_modules\firebase\lib\firebase-node.js:135:1256) 
    at ClientRequest.<anonymous> (authLinkedIn\node_modules\firebase\lib\firebase-node.js:140:308) 
    at emitOne (events.js:96:13) 
    at ClientRequest.emit (events.js:188:7) 
    at TLSSocket.socketErrorListener (_http_client.js:308:9) 
    at emitOne (events.js:96:13) 
    at TLSSocket.emit (events.js:188:7) 
    at emitErrorNT (net.js:1271:8) 
    at _combinedTickCallback (internal/process/next_tick.js:74:11) code: 'SERVER 
_ERROR' } 
Simple login authentification won't work 

Вот "WWW" исходный файл:

#!/usr/bin/env node 

/** 
* Module dependencies. 
*/ 

var app = require('../app'); 
//var debug = require('debug')('_example:server'); 
var http = require('http'); 

/** 
* Get port from environment and store in Express. 
*/ 

var port = normalizePort(process.env.PORT || '3000'); 
app.set('port', port); 

/** 
* Create HTTP server. 
*/ 

var server = http.createServer(app); 

/** 
* Listen on provided port, on all network interfaces. 
*/ 

server.listen(port); 
server.on('error', onError); 
server.on('listening', onListening); 

/** 
* Normalize a port into a number, string, or false. 
*/ 

function normalizePort(val) { 
    var port = parseInt(val, 10); 

    if (isNaN(port)) { 
    // named pipe 
    return val; 
    } 

    if (port >= 0) { 
    // port number 
    return port; 
    } 

    return false; 
} 

/** 
* Event listener for HTTP server "error" event. 
*/ 

function onError(error) { 
    if (error.syscall !== 'listen') { 
    throw error; 
    } 

    var bind = typeof port === 'string' 
    ? 'Pipe ' + port 
    : 'Port ' + port; 

    // handle specific listen errors with friendly messages 
    switch (error.code) { 
    case 'EACCES': 
     console.error(bind + ' requires elevated privileges'); 
     process.exit(1); 
     break; 
    case 'EADDRINUSE': 
     console.error(bind + ' is already in use'); 
     process.exit(1); 
     break; 
    default: 
     throw error; 
    } 
} 

/** 
* Event listener for HTTP server "listening" event. 
*/ 

function onListening() { 
    var addr = server.address(); 
    var bind = typeof addr === 'string' 
    ? 'pipe ' + addr 
    : 'port ' + addr.port; 
    //debug('Listening on ' + bind); 
    console.log('Listening on ' + bind); 
} 
+0

Это в значительной степени HTTP-сервер по умолчанию, который поставляется с экспресс-службой. Ваша ошибка возникает в обратном вызове где-то в вашем приложении. Отправьте свой «app.js» и дополнительный код приложения. – svens

ответ

0

Файл "index.js"

Эта линия была выполнена simpleLogin.connectDb (config.configDb.address, конф. configDb.id); Метод "connectDb" определен в simplelogin.js

var express = require('express'); 
var router = express.Router(); 
var config = require('../_config'); 

var passportLinkedIn = require('../auth/linkedin'); 
var simpleLogin = require('../auth/simplelogin.js'); 
var FirebaseTokenGenerator = require("firebase-token-generator"); 

console.log("address: " + config.configDb.address); 
console.log("id: " + config.configDb.id); 
simpleLogin.connectDb(config.configDb.address, config.configDb.id); 

router.get('/', function(req, res) { 
    res.render('index', { title: 'Express' }); 
}); 

router.get('/logout', function(req, res) { 
    req.logout(); 
    res.redirect(config.front.logoutRedirectURL); 
}); 

router.get('/auth/linkedin', passportLinkedIn.authenticate('linkedin')); 

router.get('/auth/linkedin/callback', 
    passportLinkedIn.authenticate('linkedin', { failureRedirect: config.front.failedRedirectURL }), 
    function(req, res) { 
    //res.cookie("cookie_firetoken" , req.user.firebase).send('Cookie is set'); 
    res.redirect(config.front.redirectURL + req.user.firebase) 
    }); 

router.post('/auth/asadmin', function(req, res) { 
    var password = req.body.password; 
    if (password === config.adminpassword) { 
     var tokenGen = new FirebaseTokenGenerator(config.firebase.secret); 
     var firebaseToken = tokenGen.createToken({ 
      uid: "-admin----", 
      emailAddress: "[email protected]", 
      firstName: "Admin", 
      lastName: "Admin", 
      pictureUrl: "", 
      isAdmin: true 
     }); 
     res.redirect(config.front.redirectURL + firebaseToken); 
    } 
    else { 
     res.redirect(config.front.logoutRedirectURL); 
    } 
    return; 
}); 

router.get('/auth/simplelogin/:candidateName/:uid', function(req,res){ 

    simpleLogin.checkCandidate(req.params['candidateName'], req.params['uid']).then(function(user){ 
     //user.simpleLogin = true; 
     var tokenGen = new FirebaseTokenGenerator(config.firebase.secret); 
     //console.log("user is ", user); 
     var firebaseToken = tokenGen.createToken(user); 
     console.log("Success logging in ",req.params['candidateName']); 
     res.setHeader("Access-Control-Allow-Origin", "*"); 
     res.status(200).send("/login-complete/" + firebaseToken); 
    }, function(){ 
     console.log("Failure logging in ", req.params['candidateName']); 
     res.status(500).send(config.front.failedRedirectURL); 
    }); 
    //if(login != -1){ 
    // 
    //}else{ 
    // console.log("Failure loging ", req.params['candidateName']); 
    // res.status(500).send(config.front.failedRedirectURL); 
    //} 
}); 

module.exports = router; 
0

Файл "simplelogin.js" Метод "connectDb" был назван в "index.js" и запустить ошибку с помощью метода "authHandler"

[Простой вход] Вход с ошибкой!

var firebase = require('firebase'); 
    var myFirebaseRef = {};  
    var candidateList = {}; 

    // Callback: Log the authentification 
    function authHandler(error, authData) { 
     if (error) { 
      console.log("[Simple Login] Login Failed!", error); 
      console.log("Simple login authentification won't work") 
     } else { 
      console.log("Authenticated successfully with payload:", authData); 
     } 
    } 

    module.exports = { 

     //error handling 
     //errorProcessed: true, 
    //log into the database 
     connectDb: function (dbAddress, authId) { 

      // Reference Firebase 
      var path = dbAddress + "/candidats/"; 
      myFirebaseRef = new Firebase(path); 
      myFirebaseRef.authWithPassword(authId, authHandler); 

      myFirebaseRef.once("value", function(snapshot){ 
       candidateList = snapshot.val(); 
       if(candidateList) { 
        console.log('---- Databases connected, ready to use ---- '); 
       }else{ 
        console.log('Unable to access Firebase, simple login authentification unavailable'); 
       } 
      }) 
     }, 

     checkCandidate: function (candidateName, uid) { 
      return new Promise(function(success, failure) { 
        //console.log("test***** ", myFirebaseRef.orderByChild('uid').beginAt(uid).endAt('uid').once("value", function(snapshot){return snapshot})); 
        myFirebaseRef.once("value", function (snapshot) { 
         candidateList = snapshot.val(); 
         //console.log("test ", candidateList['-KF3hLx_2Ws7Qlr-MIlM']); 
        }); 

        if (!candidateList) { 
         console.log("Unable to access database, refusing connection from ", candidateName); 
         return failure(); 
        } 

        var found = false; 
        var answer = -1; 
        //var index = 0; 
        //console.log("LIST *** ", candidateList); 
        Object.keys(candidateList).forEach(function (cKey) { 
        //while (index < candidateList.length) { 
         //console.log("Searching ", candidateName, " in ", candidateList[cKey]); 
         if (candidateList[cKey].firstName.toLowerCase() == candidateName.toLowerCase() && candidateList[cKey].uid.toLowerCase() == uid.toLowerCase()) { 
          found = true; 
          answer = cKey; 
         } 
         //index++; 
        }); 
       if(found) 
       { 

        //myFirebaseRef.child(answer).update("simpleLogin", true); 
        candidateList[answer].simpleLogin = true; 
        myFirebaseRef.child(answer).update(candidateList[answer]); 
        return success({ 
         uid: candidateList[answer].uid, 
         firstname: candidateList[answer].firstName, 
         lastname: candidateList[answer].lastName, 
         emailAddress: candidateList[answer].emailAddress, 
         pictureUrl: "", 
         isAdmin: false 
        }); 
       }else { 
        return failure(); 
       } 
       } 
      ) 
     } 

    }; 
Смежные вопросы