Firebase:发生未知服务器错误

时间:2016-10-26 14:15:07

标签: node.js firebase firebase-realtime-database

作为NodeJS的初学者,我发现了关于这个框架的新东西,非常有趣。

所以我试图写一个与FireBase数据库通信的NodeJS脚本,但是这个错误被捕获了

请问您有关于此错误的任何想法吗?

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

这是&#34; www&#34;文件来源:

#!/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);
}

2 个答案:

答案 0 :(得分:0)

档案“index.js”

此行已执行 simpleLogin.connectDb(config.configDb.address,config.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: "admin@example.org",
          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;

答案 1 :(得分:0)

文件&#34; simplelogin.js&#34; 方法&#34; connectDb&#34;被称为&#34; index.js&#34;并通过方法&#34; authHandler&#34;

启动错误

[简单登录]登录失败!

 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();
                }
                }
            )
        }

    };