Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将最终用户登录到单页应用程序,并将其重定向到单页应用程序?_Javascript_Node.js_Backbone.js_Express_Passport.js - Fatal编程技术网

Javascript 如何将最终用户登录到单页应用程序,并将其重定向到单页应用程序?

Javascript 如何将最终用户登录到单页应用程序,并将其重定向到单页应用程序?,javascript,node.js,backbone.js,express,passport.js,Javascript,Node.js,Backbone.js,Express,Passport.js,如何使用Backbone.js将最终用户登录到单页应用程序,并将其重定向到单页应用程序。Express.js和passport.js 我有passport、mongo.db、express和backbone都在处理我的申请。但是,在成功登录后,我想加载单个页面、主干js和web应用程序。到目前为止,我的登录系统运行良好。但是,当我将用户重定向到应用程序时,在成功登录之后,出于某种原因,它只会重定向回登录页面。我使用了控制台日志来确保服务器端的登录代码没有问题,并且一切正常。奇怪的是,当我打开ch

如何使用Backbone.js将最终用户登录到单页应用程序,并将其重定向到单页应用程序。Express.js和passport.js

我有passport、mongo.db、express和backbone都在处理我的申请。但是,在成功登录后,我想加载单个页面、主干js和web应用程序。到目前为止,我的登录系统运行良好。但是,当我将用户重定向到应用程序时,在成功登录之后,出于某种原因,它只会重定向回登录页面。我使用了控制台日志来确保服务器端的登录代码没有问题,并且一切正常。奇怪的是,当我打开chrome developer tools,查看标题和响应时,我得到了正确的索引页,但它没有加载到浏览器中,Url仍然是
http://localhost:3000/login

以下是我怀疑一定是罪魁祸首的代码:

参见编辑#2

我已经尝试了这两种
res.sendfile(uu dirname+'/public/index.html')
res.render('index',{user:req.user})在我的基本(“/”)路由中,但它们似乎都没有加载index.html。请注意,public/index.html和ejs索引本质上是相同的文件。我开始在客户端加载整个应用程序,但现在我正试图将主index.html文件移到服务器端,这样它就可以得到密码保护

请让我知道,如果有任何问题,将帮助我更好地解释这个问题,或者如果有更多的代码,你想看到。我真的很想弄清楚这件事

编辑正如您在我的浏览器屏幕截图中看到的,我只有简单的表单。提交表单时,我确实在响应中返回了所需的页面,但它没有加载到浏览器中。控制台中也出现了加载资源失败的错误,但由于某种原因,它无法加载/登录,即使我正在尝试加载索引。

编辑#2虽然我不喜欢粘贴无休止的代码块,但我认为解决这个问题的唯一方法是粘贴无休止的代码块。 这里是server.js的全部荣耀——减去一些不相关的api路由:

var express = require('express')
  , http = require('http')
  , passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy
  , bcrypt = require('bcrypt')
  , SALT_WORK_FACTOR = 10
  , mongoose = require('mongoose')
  , path = require('path');

var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(3000);

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.engine('ejs', require('ejs-locals'));
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser('your secret here'));
  app.use(express.session());
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
    app.use( express.errorHandler({ dumpExceptions: true, showStack: true }));
});

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

//Connect to database
var db = mongoose.connect( 'mongodb://localhost/attorneyapp' );

/*
|-------------------------------------------------------------------------------
| Schemas
|-------------------------------------------------------------------------------
*/
var userSchema = mongoose.Schema({
  username: { type: String, required: true, unique: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true},
});
// Bcrypt middleware
userSchema.pre('save', function(next) {
    var user = this;

    if(!user.isModified('password')) return next();

    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
        if(err) return next(err);

        bcrypt.hash(user.password, salt, function(err, hash) {
            if(err) return next(err);
            user.password = hash;
            next();
        });
    });
});
// Password verification
userSchema.methods.comparePassword = function(candidatePassword, cb) {
    bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
        if(err) return cb(err);
        cb(null, isMatch);
    });
};
var Client = new mongoose.Schema({
    first_name: String,
    last_name: String,
    status: String,
});
var Case = new mongoose.Schema({
    case_name: String,
    status: String,
});

/*
|-------------------------------------------------------------------------------
| Models
|-------------------------------------------------------------------------------
*/
var User = mongoose.model( 'User', userSchema );
var ClientModel = mongoose.model( 'Client', Client );
var CaseModel = mongoose.model( 'Case', Case );

// Seed a user
// var user = new User({ username: 'bob', email: 'bob@example.com', password: 'secret' });
// user.save(function(err) {
//   if(err) {
//     console.log(err);
//   } else {
//     console.log('user: ' + user.username + " saved.");
//   }
// });

// Passport session setup.
//   To support persistent login sessions, Passport needs to be able to
//   serialize users into and deserialize users out of the session.  Typically,
//   this will be as simple as storing the user ID when serializing, and finding
//   the user by ID when deserializing.
passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function (err, user) {
    done(err, user);
  });
});
// Use the LocalStrategy within Passport.
//   Strategies in passport require a `verify` function, which accept
//   credentials (in this case, a username and password), and invoke a callback
//   with a user object.  In the real world, this would query a database;
//   however, in this example we are using a baked-in set of users.
passport.use(new LocalStrategy(function(username, password, done) {
  User.findOne({ username: username }, function(err, user) {
    if (err) { 
        console.log('error: ', err);
        return done(err); 

    }
    if (!user) { 
        console.log('Unknown user ', username);  
        return done(null, false, { message: 'Unknown user ' + username }); 
    }
    user.comparePassword(password, function(err, isMatch) {
      if (err){
        console.log('error: ', err);

        return done(err);
      } 
      if(isMatch) {
        console.log('it is a match');
        return done(null, user);
      } else {
        console.log('invalid password');

        return done(null, false, { message: 'Invalid password' });
      }
    });
  });
}));
/*
|-------------------------------------------------------------------------------
| User
|-------------------------------------------------------------------------------
*/
// POST /login
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  If authentication fails, the user will be redirected back to the
//   login page.  Otherwise, the primary route function function will be called,
//   which, in this example, will redirect the user to the home page.
//
//   curl -v -d "username=bob&password=secret" http://127.0.0.1:3000/login
//   
/***** This version has a problem with flash messages
app.post('/login', 
  passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }),
  function(req, res) {
    res.redirect('/');
  });
*/

// POST /login
//   This is an alternative implementation that uses a custom callback to
//   acheive the same functionality.
app.get('/', function(req, res){
    console.log('base router is being called');

    // res.sendfile(__dirname + '/public/index.html');
    res.render('index');
});
app.get('/login', function(req, res) {
    return res.render('login');
});

app.post('/login', function(req, res, next) {

  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err) }
    if (!user) {
        console.log('NOT USER', info.message);

      req.session.messages =  [info.message];

      return res.redirect('/login');

    }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      console.log('YES USER is loged in');
      // return res.sendfile(__dirname + '/public/index.html');
      return res.redirect('/');


    });
  })(req, res, next);
});

app.get('/users', function(req, res){
  return User.find( function( err, users ) {
        if( !err ) {
            return res.send( users );
        } else {
            return console.log( err );
        }
    });
});
另外,不确定这是否相关,但这是我的目录和文件结构。
尝试返回空值。(实际上没有定义)

我是说

res.redirect('/');
return;
而不是

return res.redirect('/');

不要在登录时使用
res.render('index'
…和
res.sendfile(
…在登录时!它会将
index.html
中的响应数据发送到
/login
页面上的客户端!

我试过了,但仍然不起作用。不过,我再也不会在控制台中遇到加载资源失败的错误。尝试删除奇怪的
(req,res,下一步)
在代码的末尾。似乎这没有任何作用。我尝试删除,但在用户经过身份验证后,知道不再调用“app.get(“/”,function(req,res)”