为什么我的ejs没有渲染重定向?

时间:2015-12-15 12:19:54

标签: javascript node.js mongodb express

我已经制作了一个表单。在成功提交表单后,我想将页面重定向到thankyou页面(另一个ejs)视图。不知何故,如果我使用res.redirect()它不起作用,但使用res.send('谢谢你')它工作正常。

以下是我app.js的代码:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var routes = require('./routes/index');
var users = require('./routes/users');
var thankyou = require('./routes/thankyou');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
var engine = require('ejs-locals');
app.engine('ejs', engine);
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

mongoose.connect('mongodb://localhost/my-data');

app.use('/', routes);
app.use('/users', users);
app.use('/thankyou', thankyou);

var Schema = new mongoose.Schema({
    name      : String,
    email     : String
});

var user = mongoose.model('Users', Schema);


app.post('/test',function(req,res){
  new user({
      email : req.body.email,
      name : req.body.name
  }).save(function(err, doc){
    if(err){
      console.log('boo');
    }
    else{
      console.log('innner');
      res.redirect("/thankyou");
       res.end();

    }
  })
})

thankyou route:

var express = require('express');
var router = express.Router();
router.get('/thankyou', function(req, res) {
 res.render('thankyou');
});

module.exports = router;

thankyou view

<h2>THANKS/h2>

1 个答案:

答案 0 :(得分:2)

此:

app.use('/thankyou', thankyou);

......结合这个:

router.get('/thankyou', ...);

...创建一个匹配/thankyou/thankyou的路线。

相反,你可能想要这个:

router.get('/', ...);