【问题标题】:Firebase : Unknown server error occurredFirebase:发生未知的服务器错误
【发布时间】:2016-10-27 15:46:01
【问题描述】:

作为一个 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

这里是“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);
}

【问题讨论】:

  • 这几乎是 express 附带的默认 HTTP 服务器。您的错误发生在应用程序某处的回调中。也发布您的app.js 和其他应用代码。

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


【解决方案1】:

文件“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;

【讨论】:

    【解决方案2】:

    文件“simplelogin.js” 在“index.js”中调用方法“connectDb”并通过方法“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();
                    }
                    }
                )
            }
    
        };
    

    【讨论】:

      猜你喜欢
      • 2020-06-28
      • 1970-01-01
      • 1970-01-01
      • 2020-06-22
      • 2021-12-31
      • 2022-01-09
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多