如何在Express js中重定向到下一页

时间:2017-07-23 11:19:59

标签: javascript node.js express handlebars.js

 index.hbs

    <h1> {{LoginTitle}} </h1>
      <form action="/login" method="post">
       <label for="Email">Email</label>
         <input type="text" name="Email" id="Email" placeholder="Email">
        <label for="password">password</label>
         <input type="text" name="password" id="password 
            placeholder="password">
         <input type ="button" value="SignIn"  onClick="'/welcome'">
        </form>

index.js

var express = require('express');
var router = express.Router();
var mongo = require('mongodb');
var url = 'mongodb://localhost:27017/test';

/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { LoginTitle: 'HOUSEHOLD EXPENSE' });
});

router.get('/login', function(req, res, next) {
res.render('welcome', { welcome : 'hey' });
});

router.post('/login', function(req,res,next){
if(req.body.Email == Email && req.body.password == password){
    res.render('welcome');
 }
 else
 {
  res.render('/');
  }

  });

  module.exports = router;

welcome.hbs

  <h1> {{ welcome }}</h1>

  <p> Hello Mr User</p>

我正在使用快速把手。成功登录后,它不会进入下一页welcome.hbs任何人都可以让我知道我在做什么错误

2 个答案:

答案 0 :(得分:0)

if(req.body.Email == Email && req.body.password == password){
res.render('welcome');
}

应该是

if(req.body.Email == Email && req.body.password == password){
res.render('welcome', { welcome : 'hey' });
}

在index.hbs

<input type="text" name="password" id="password" placeholder="password">
<input type ="submit" value="SignIn">

答案 1 :(得分:0)

应该是:

var express = require('express');
var router = express.Router();
var mongo = require('mongodb');
var url = 'mongodb://localhost:27017/test';

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { LoginTitle: 'HOUSEHOLD EXPENSE' });
});

route.get('/welcome', function(req, res) {
    res.render('welcome', {welcome: 'Hey'});
}

router.post('/login', function(req,res,next){
    if(req.body.Email == Email && req.body.password == password){
         res.redirect('/welcome'); // Redirect to /welcome if success
    }
    else {
         res.redirect('/login'); // Redirect to /login if login fail
    }

});

module.exports = router;