1

我是 Node 新手,有一个 Node、Express 和 Passport 设置并且看起来可以正常工作。也就是说,我看不到任何错误消息。

问题是当我进入登录页面并尝试登录时,没有任何反应。单击按钮后页面刷新,但未采取任何操作。

我已经粘贴了下面的代码。

这是我提交表单时的终端输出:

08:19:53 web.1  | POST /login 302 3ms - 68
08:19:53 web.1  | GET /login 304 11ms
08:19:53 web.1  | GET /stylesheets/base.css 304 1ms

这是登录视图(Jade):

- if (message)
  p
    strong =message

form(method="post", action="/login")
  fieldset
    label(for="username") Username
    input.text-input(type="text", name="username")

    label(for="password") Password
    input.text-input(type="password", name="password")

    button.btn-submit(type="submit") Login!

    a.btn-cancel(href="/") Cancel

这是最初调用登录页面的代码(为了清楚起见,我取出了其他东西):

应用程序.js

app.get("/login", routes.login);

路线/index.js

(function() {
  var Post;

  Post = require('../models/Post');

  module.exports = {
    login: function(req, res) {
      return res.render("login", {
        user: req.user,
        message: req.flash("Login error!"),
        title: "Login | David Yeiser"
      });
    }
  };

}).call(this);

这是处理帖子的app.js部分:

app.post("/login", passport.authenticate("local", {
    failureRedirect: "/login",
    failureFlash: true
}), function(req, res) {
    return res.redirect("/office");
});

最后,这是整个app.js

(function() {
  var LocalStrategy, app, express, findById, findByUsername, flash, http, mongoose, passport, path, routes, user, users, util;

  express = require('express');
  routes = require('./routes');
  user = require('./routes/user');
  http = require('http');
  path = require('path');
  mongoose = require('mongoose');
  passport = require('passport');
  flash = require('connect-flash');
  util = require('util');
  LocalStrategy = require('passport-local').Strategy;

  users = [
    {
      id: 1,
      username: 'bob',
      password: 'secret',
      email: 'bob@me.com',
      id: 2,
      username: 'nancy',
      password: 'secrettoo',
      email: 'nancy@me.com'
    }
  ];

  findById = function(id, fn) {
    var idx;
    idx = id - 1;
    if (users[idx]) {
      return fn(null, users[idx]);
    } else {
      return fn(new Error('User does not exist'));
    }
  };

  findByUsername = function(username, fn) {
    var i, len;
    i = 0;
    len = users.length;
    while (i < len) {
      user = users[i];
      if (user.username === username) {
        return fn(null, user);
      }
      i++;
    }
    return fn(null, null);
  };

  passport.serializeUser(function(user, done) {
    return done(null, user.id);
  });

  passport.deserializeUser(function(id, done) {
    return findById(id, function(err, user) {
      return done(err, user);
    });
  });

  passport.use(new LocalStrategy(function(username, password, done) {
    return process.nextTick(function() {
      return findByUsername(username, function(err, user) {
        if (err) {
          return done(err);
        }
        if (!user) {
          return done(null, false, {
            message: "Unknown user " + username
          });
        }
        if (user.password !== password) {
          return done(null, false, {
            message: "Invalid password"
          });
        }
        return done(null, user);
      });
    });
  }));

  app = express();

  app.configure(function() {
    app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.cookieParser());
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.session({
      secret: 'keyboard cat'
    }));
    app.use(flash());
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(app.router);
    return app.use(express["static"](path.join(__dirname, 'public')));
  });

  app.configure('development', function() {
    mongoose.connect('mongodb://localhost/davidyeiser_dev');
    return app.use(express.errorHandler());
  });

  app.get("/", routes.index);

  app.get("/login", routes.login);

  app.post("/login", passport.authenticate("local", {
    failureRedirect: "/login",
    failureFlash: true
  }), function(req, res) {
    return res.redirect("/office");
  });

  app.get("/logout", function(req, res) {
    req.logout();
    return res.redirect("/");
  });

  app.get("/post/new", routes.newPost);
  app.post("/post/new", routes.addPost);
  app.get("/post/:id", routes.viewPost);
  app.get("/users", user.list);

  http.createServer(app).listen(app.get("port"), function() {
    return console.log("Express server listening on port " + app.get("port"));
  });

}).call(this);

您看到的大部分内容来自 Passport Express 3 示例: https ://github.com/jaredhanson/passport-local/blob/master/examples/express3/

我很感谢你能给我的任何帮助。

4

1 回答 1

2

啊哈!用户数组构造不正确。

  users = [
    {
      id: 1,
      username: 'bob',
      password: 'secret',
      email: 'bob@me.com',
      id: 2,
      username: 'nancy',
      password: 'secrettoo',
      email: 'nancy@me.com'
    }
  ];

需要:

  users = [
    {
      id: 1,
      username: 'bob',
      password: 'secret',
      email: 'bob@me.com'
    },
    {
      id: 2,
      username: 'nancy',
      password: 'secrettoo',
      email: 'nancy@me.com'
    }
  ];

我发现它的方式是我只是减少到一个用户(在大约 1,000 件其他事情中),然后最终意识到这是错误的。其他一切都保持不变。

(之前没抓到的原因是因为我每次都用“bob”,从来没想过要试试“nancy”)

于 2013-02-16T05:37:25.570 回答