2015-06-18 1 views
-1

Я изучаю ExpressJS. До сих пор я установил простое приложение todo с аутентификацией пользователя с помощью PassportJS. Я использую Mongoose для репозитория. В Интернете нет ничего, чтобы объяснить странное поведение, которое я вижу с настройкой маршрута.Приложение NodeJs + ExpressJs нечетное поведение

Сценарий:

  • Когда я попал получить/паспорт он направит на страницу паспорта (Логин/регистрации)
  • Когда я попал получить/aslkdjf он направит на страницу паспорта, если пользователя не вошли в систему, иначе она будет направлять в файл
    /public/index.html)
  • Когда я попал получить/он должен направить на страницу паспорта, если пользователь не вошел в систему, но она идет/общественности /index.html и мое TODO приложение потерпит неудачу, как req.user.username под/API/Todos является undefiend

Как ни странно, когда я удалить router.get ('/ *', ... конфигурации, мое приложение будет по-прежнему перейдите в public/index.html, когда я нахожу базовый путь '/', но не тогда, когда я нажимаю '/ asdfa'.

... 
 
    
 
    function loggedIn(req, res, next) { 
 
     if (req.user) { 
 
      next(); 
 
     } else { 
 
      res.redirect('/passport'); 
 
     } 
 
    } 
 

 
    var router = express.Router(); 
 
// passport ---------------------------------------------------------------- 
 
// get passport page 
 
router.get('/passport', notLoggedIn, function(req, res) { 
 
    res.sendfile('./public/passport.html'); 
 
}); 
 

 
// post login 
 
router.post('/login', passport.authenticate('login', { 
 
    successRedirect: '/', 
 
    failureRedirect: '/passport', 
 
    failureFlash: true 
 
})); 
 

 
// post registration 
 
router.post('/signup', passport.authenticate('signup', { 
 
    successRedirect: '/', 
 
    failureRedirect: '/passport', 
 
    failureFlash: true 
 
})); 
 

 
router.get('/logout', function(req, res) { 
 
    req.session.destroy(); 
 
    req.logout(); 
 
    res.redirect('/'); 
 
}); 
 

 
// api --------------------------------------------------------------------- 
 
// get all todos 
 
router.get('/api/todos', function(req, res) { 
 

 
    // use mongoose to get all todos in the database 
 
    Todo.find({owner: req.user.username}, function(err, todos) { 
 

 
     // if there is an error retrieving, send the error. nothing after res.send(err) will execute 
 
     if (err) 
 
      res.send(err) 
 

 
     res.json(todos); // return all todos in JSON format 
 
    }); 
 
}); 
 

 
// create todo and send back all todos after creation 
 
router.post('/api/todos', function(req, res) { 
 

 
    // create a todo, information comes from AJAX request from Angular 
 
    Todo.create({ 
 
     owner: req.user.username, 
 
     text : req.body.text, 
 
     done : false 
 
    }, function(err, todo) { 
 
     if (err) 
 
      res.send(err); 
 

 
     // get and return all the todos after you create another 
 
     Todo.find({owner: req.user.username}, function(err, todos) { 
 
      if (err) 
 
       res.send(err) 
 
      res.json(todos); 
 
     }); 
 
    }); 
 

 
}); 
 

 
// delete a todo 
 
router.delete('/api/todos/:todo_id', function(req, res) { 
 
    Todo.remove({ 
 
     _id : req.params.todo_id 
 
    }, function(err, todo) { 
 
     if (err) 
 
      res.send(err); 
 

 
     // get and return all the todos after you create another 
 
     Todo.find({owner: req.user.username}, function(err, todos) { 
 
      if (err) 
 
       res.send(err) 
 
      res.json(todos); 
 
     }); 
 
    }); 
 
}); 
 

 
// application ------------------------------------------------------------- 
 
router.all('*', loggedIn); 
 
router.get('/*', function(req, res) { 
 
    res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end) 
 
}); 
 

 
    app.use('/', router); 
 
    app.listen(3000); 
 
    console.log("App listening on port 3000");

Может кто-нибудь объяснить мне, что происходит? Все, что я хочу достичь, - это заставить пользователя перенаправлять пользователя на страницу входа, когда они не вошли в систему, и они переходят на сайт www.myapp.com/

ответ

0

По-видимому, проблема в том, что HTML по умолчанию находит индекс .html в любой папке в корне. Когда я изменяю html-файл на другое, например abc.html, проблема решена. Кажется, это ошибка.

 Смежные вопросы

  • Нет связанных вопросов^_^