连接节点js中的闪存不工作

时间:2018-04-17 13:49:03

标签: node.js express

我正在尝试使用app.js文件中的以下注册码在我的数据库中注册用户。

请参阅注册路线app.post。问题是,当我运行应用程序时,它会抛出错误说

req未定义,该行显示在我创建flash消息的位置:

req.flash(' error_msg','用户名已注册');

我尝试注释掉这一行,然后我只为其res.redirect函数的下一行得到了相同的错误。

似乎我的req和res在我的注册函数中不可用。我是Node的新手所以请耐心等待:-)

const express = require('express');
const path = require('path');
const exphbs = require('express-handlebars');
const methodOverride = require('method-override');
const flash = require('connect-flash');
const session =require('express-session');
const bodyParser = require('body-parser');
const errorHandler = require('errorhandler');
const routes = require('./routes');
const nconf = require('./config');
const setAuthUser = require('./middlewares/setAuthUser');
const neo4jSessionCleanup = require('./middlewares/neo4jSessionCleanup');
const writeError = require('./helpers/response').writeError;

const uuid = require('node-uuid');
const randomstring = require("randomstring");
const _ = require('lodash');


var Users = require('./models/users');
var loginRequired = require('./middlewares/loginRequired');
var dbUtils = require('./neo4j/dbUtils');


const app = express();


  // Body Parser middleware
  app.use(bodyParser.urlencoded({ extended: false}));
  app.use(bodyParser.json());

  var api = express.Router();

app.use(nconf.get('api_path'), api);

// Flash middleware
app.use(flash());


  //api custom middlewares:
api.use(setAuthUser);
api.use(neo4jSessionCleanup);

  // Handlebars middleware
app.engine('handlebars', exphbs({
    defaultLayout: 'main'
  }));
  app.set('view engine', 'handlebars');

  // static folder
app.use(express.static(path.join(__dirname, 'public')));

//method override middleware
api.use(methodOverride('_method'));

// Express Session middleware
app.use(session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true,
}));

// global variables
app.use(function(req, res, next){
    res.locals.success_msg = req.flash('success_msg');
    res.locals.error_msg = req.flash('error_msg');
    res.locals.error = req.flash('error');
    res.locals.user = req.user || null;
    next();
});

// index route
app.get('/', (req, res)=>{
    const title = 'welcome1';
    res.render('index', {
        title: title
    });
});


// User Register Route
    app.get('/users/register', (req, res) => {
        res.render('users/register');
  });

  app.post('/users/register',(req, res,next) => {
        var username = req.body.username;
        var password = req.body.password;

    if (!username) {
      //throw {username: 'This field is required.', status: 400};
      req.flash('error_msg', 'username field is required');
      res.redirect('/users/register');
    }
    if (!password) {
      //throw {password: 'This field is required.', status: 400};
      req.flash('error_msg', 'password field is required');
      res.redirect('/users/register');
    }

    register(dbUtils.getSession(req), username, password)
      .then(response => {
        req.flash('success_msg', 'You are now registered');
        res.redirect('/users/login');
      })
      .catch(next);
  });

//api routes
//api.post('/register', routes.users.register);
api.post('/login', routes.users.login);
api.get('/users/me', routes.users.me);
api.get('/movies', routes.movies.list);
api.get('/movies/recommended', routes.movies.getRecommendedMovies);
api.get('/movies/rated', routes.movies.findMoviesRatedByMe);
api.get('/movies/:id',  routes.movies.findById);
api.get('/movies/genre/:id',  routes.movies.findByGenre);
api.get('/movies/daterange/:start/:end', routes.movies.findMoviesByDateRange);
api.get('/movies/directed_by/:id', routes.movies.findMoviesByDirector);
api.get('/movies/acted_in_by/:id', routes.movies.findMoviesByActor);
api.get('/movies/written_by/:id', routes.movies.findMoviesByWriter);
api.post('/movies/:id/rate', routes.movies.rateMovie);
api.delete('/movies/:id/rate', routes.movies.deleteMovieRating);
api.get('/people', routes.people.list);
api.get('/people/:id', routes.people.findById);
api.get('/people/bacon', routes.people.getBaconPeople);
api.get('/genres', routes.genres.list);

//api error handler
api.use(function(err, req, res, next) {
  if(err && err.status) {
    writeError(res, err);
  }
  else next(err);
});


var register = function (session, username, password) {
  return session.run('MATCH (user:User {username: {username}}) RETURN user', {username: username})
    .then(results => {
      if (!_.isEmpty(results.records)) {
        //throw {username: 'username already in use', status: 400}
        req.flash('error_msg', 'Username already registered');
        res.redirect('/users/register');
      }
      else {
        return session.run('CREATE (user:User {id: {id}, username: {username}, password: {password}, api_key: {api_key}}) RETURN user',
          {
            id: uuid.v4(),
            username: username,
            password: hashPassword(username, password),
            api_key: randomstring.generate({
              length: 20,
              charset: 'hex'
            })
          }
        ).then(results => {
            return new User(results.records[0].get('user'));
          }
        )
      }
    });
};


const port = 3000;

app.listen(port, () => {
    console.log(`Server started on port ${port}`);
});

1 个答案:

答案 0 :(得分:0)

由于req功能无法访问resregister,因此只能在中间件中访问它们,因此您必须将这些对象作为参数:

在函数定义中:

var register = function (session, username, password, req, res) { ... };

在函数调用中:

register(dbUtils.getSession(req), username, password, req, res)
  .then(response => {
    req.flash('success_msg', 'You are now registered');
    res.redirect('/users/login');
  })
  .catch(next);