2016-10-02 60 views
0

我正在學習NodeJS,我使用EJS作爲模板引擎。但是,每當我點擊register按鈕我的註冊頁面我收到一個錯誤,title is not defined。 這是我的代碼。使用Express在EJS模板引擎上獲取錯誤「標題未定義」

users.js

var express = require('express'); 
var router = express.Router(); 
var multer = require('multer'); 
var uploads = multer({dest: './uploads'}); 

/* GET users listing. */ 
router.get('/', function(req, res, next) { 
    res.send('respond with a resource'); 
}); 

router.get('/register', function(req, res, next) { 
    res.render('register',{ 
    'title': 'Register' 
    }); 
}); 

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

router.post('/register', uploads.single('profileImage'), function(req, res, next){ 
    var name = req.body.name; 
    var email = req.body.email; 
    var username = req.body.username; 
    var password = req.body.password; 
    var password2 = req.body.password2; 


    //Check for image field 

    if(req.file){ 
     console.log('Uploading file.....'); 

     var profileImageOriginalName = req.files.profileimage.originalname; 
     var profileImageName = req.files.profileimage.name; 
     var profileImageMime = req.files.profileimage.mimetype; 
     var profileImagePath = req.files.profileimage.path; 
     var profileImageExt = req.files.profileimage.extension; 
     var profileImageSize = req.files.profileimage.size; 
    } 
    else{ 
     //set a default image 
     var profileImageName = 'noimage.png'; 
    } 

    //Form Validation 
    req.checkBody('name','This field is required').notEmpty(); 
    req.checkBody('email','This field is required').notEmpty(); 
    req.checkBody('email','Invalid Email').isEmail(); 
    req.checkBody('username','This field is required').notEmpty(); 
    req.checkBody('password','This field is required').notEmpty(); 
    req.checkBody('password2','Passwords do not match').equals(req.body.password); 

    //check for errors 
    var errors = req.validationErrors(); 
    if(errors){ 
     res.render('register',{ 
      errors: errors, 
      name: name, 
      email: email, 
      username: username, 
      password: password, 
      password2: password2 
     }); 
    } 
    else{ 
     var newUser = new User({ 
      name: name, 
      email: email, 
      username: username, 
      password: password, 
      profileimage: profileImageName 
     }); 
     //Create user 
     /*User.createUser(newUser, function(err, user){ 
      if(err) throw err; 
      console.log(user);  
     });*/ 

     //success message 
     req.flash('success', 'Your account registered successfully'); 
     res.location('/'); 
     res.redirect('/'); 
    } 
}); 

module.exports = router; 

head.ejs

<title><%= title %></title> 
<link rel='stylesheet' href='/stylesheets/bootstrap.css' /> 
<link rel='stylesheet' href='/stylesheets/style.css' /> 

header.ejs

<nav class="navbar navbar-inverse navbar-fixed-top"> 
    <div class="container"> 
    <div class="navbar-header"> 
     <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> 
     <span class="sr-only">Toggle navigation</span> 
     <span class="icon-bar"></span> 
     <span class="icon-bar"></span> 
     <span class="icon-bar"></span> 
     </button> 
     <a class="navbar-brand" href="#">Project name</a> 
    </div> 
    <div id="navbar" class="collapse navbar-collapse"> 
     <ul class="nav navbar-nav"> 
     <li <% if (title == "Members") { %>class="active" <% } %> ><a href="/">Members</a></li> 
     <li <% if (title == "Register") { %>class="active" <% } %> ><a href="https://stackoverflow.com/users/register">Register</a></li> 
     <li <% if (title == "Login") { %>class="active" <% } %> ><a href="https://stackoverflow.com/users/login">Log In</a></li> 
     </ul> 
     <ul class="nav navbar-nav navbar-right"> 
     <li><a href="https://stackoverflow.com/users/logout">Log Out</a></li> 
     </ul> 
    </div><!--/.nav-collapse --> 
    </div> 
</nav> 

個register.ejs

<!DOCTYPE html> 
<html> 
    <head> 
    <% include ./partials/head.ejs %> 
    </head> 
    <body> 

    <div class="container"> 
     <% include ./partials/header.ejs %> 
     <h1>Register</h1> 
     <p>Please Register using the below form</p> 
     <form method="post" action="https://stackoverflow.com/users/register" enctype="multipart/form-data"> 
     <div class="form-group"> 
      <label>Name</label> 
      <input class="form-control" type="text" name="name" placeholder="Enter your name"> 
     </div> 
     <div class="form-group"> 
      <label>Email</label> 
      <input class="form-control" type="email" name="email" placeholder="Enter your email"> 
     </div> 
     <div class="form-group"> 
      <label>Username</label> 
      <input class="form-control" type="text" name="username" placeholder="Enter your username"> 
     </div> 
     <div class="form-group"> 
      <label>Password</label> 
      <input class="form-control" type="password" name="password" placeholder="Enter your Password"> 
     </div> 
     <div class="form-group"> 
      <label>Confirm Password</label> 
      <input class="form-control" type="password" name="password2" placeholder="Confirm your Password"> 
     </div> 
     <div class="form-group"> 
      <label>Profile Image</label> 
      <input class="form-control" type="file" name="profileImage"> 
     </div> 
     <button class="btn btn-default" name="submit" type="submit" value="Register">Register</button> 
     </form> 
    </div> 
    </body> 
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> 
    <script type="text/javascript" src="/javascript/bootstrap.js"></script> 
</html> 

我沒有得到爲什麼發生這種情況。我試過this solution但它不工作。任何幫助,將不勝感激。

回答

0

當請求遇到/時,我無法準確理解您的路由器將重定向到的位置。

router.get('/', function(req, res, next) { 
    res.send('respond with a resource'); 
}); 

通常爲/它重定向到index模板。例如,使用EJS,您可以重定向到模板。

router.get('/', function(req, res, next) { 
    res.render('index', {param: value}); 
}); 

什麼似乎發生的事情是,當你的請求達到/,它重定向到,其中包括具有head.ejs的模板,需要發送給它的title參數。

在你的路線到達,你正確地發送這樣的:

router.get('/register', function(req, res, next) { 
    res.render('register',{ 
     'title': 'Register' 
    }); 
}); 

但是,當你的要求擊中門柱方法,所有的邏輯之後,你不重定向到一個模板,您要重定向它到/,沒有參數。如果您的/路線使用您的head.ejs訪問模板,那就是您遇到此錯誤的原因。

在你的情況下,即使你重定向到index.ejsmessageUserAdded.ejs(例如),我會再與render方法調用它來進行渲染EJS模板(而不是res.location('/');res.redirect('/');),如下:

res.render('index', {title: 'User Successfully Added'}); 

只是爲了增加一種可能性,您可以爲成功的消息創建一個模板,然後您可以將消息傳遞給它,爲每個頁面定製您已做好的事情。作爲一個例子,一個這樣的模板:

successfulMessage。EJS

<html> 
    <head><title> <%=title%> </title></head> 
<body> 
    <h1>This works!</h1> 
    <h2> <%=messageTitle%> </h2> 
    <span> <%=messageDetails%> </span> 
</body> 
</html> 

,然後用它在你的信息:

// After all the logic 
res.render('successfulMessage', { 
    title: 'Success', 
    messageTitle: 'Account Created', 
    messageDetails: 'John has been added to our database!' 
}) 

希望它可以幫助你解決這個問題。

+0

嘗試'res.render'而不是'res.location',但仍然是相同的錯誤 – Sinscary

+0

你使用res.render('yourTemplate',{title:'your title'})?你可以在你的問題中添加你重定向的模板嗎?另外,你是否保留了到/通過res.send('回覆資源')的路線? – Tom

+0

我把'res.render('index',{title:'Members'}',但仍然有同樣的錯誤。 – Sinscary