成功插入后,nodejs / Expressjs重定向

时间:2017-10-24 12:38:08

标签: node.js express redirect router ejs

我正在使用EJS作为模板引擎在Nodejs / Expressjs中使用CRUD应用程序。

我在“views”文件夹中创建了一个文件夹,名称登录,其中我有几个文件。 Views文件夹包含我的所有.ejs文件。 现在成功插入(通过路由器)后,我想重定向到.ejs文件(登录/文件名)。但它没有用。

这是我的工作目录:

Folder directory

我添加了所有相关的路由器。

app.js:

var express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    session = require('express-session'),
    expressValidator = require('express-validator'),
    flash = require('connect-flash'),
    multer = require('multer'),
    upload = multer({dest: './app/public/uploads/uploads'}),
    app = express();

//database connection
const { Client } = require('pg');
const connectionString = 'postgres://idid:rahulpalace@localhost/idid';

// set an enviornment variable for the port number. Default set to 3000
app.set('port', process.env.PORT || 3000);

//set EJS as the template engine
app.set('view engine', 'ejs');
app.set('views', 'app/views');

//set public folder
app.use(express.static('app/public'));

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

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

//Express Messages Middleware
app.use(flash());
app.use(function (req, res, next) {
  res.locals.messages = require('express-messages')(req, res);
  next();
});

// Validator
app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));

//function to hide very long text. Show only starting 10 length text
app.locals.truncateText = function(text, length){
    var truncateText = text.substring(0, length);
    truncateText += ' ...';
    return truncateText;
}

 /* creating routes */
//index.html
app.use(require('./routes/index'));
//team.html
app.use(require('./routes/team'));
//contact.html
app.use(require('./routes/contact'));
//publication.html
app.use(require('./routes/publication'));
//admin panel
app.use(require('./routes/login/login'));
//dashboard
app.use(require('./routes/login/dashboard'));
//view publication
app.use(require('./routes/login/view_publication'));
app.use(require('./routes/login/add_publication'));
app.use(require('./routes/login/edit_publication'));
app.use(require('./routes/login/delete_publication'));

app.use(require('./routes/login/add_team'));
app.use(require('./routes/login/view_team'));
app.use(require('./routes/login/edit_team'));
//app.use(require('./routes/login/delete_team'));

//listen to requests from client
var server = app.listen(app.get('port'), function(){
    console.log('server started on '+ app.get('port'));
});

(路由器)add_team.js:

router.post('/add_team', upload.single('profileImage') ,function(req, res, next) {
  var name = req.body.name;
  var title = req.body.title;
  var description = req.body.description;
  var created = new Date();
  var isActive = true;

  if(req.file) {
    console.log('Uploading File...');
    var profileImage = req.file.filename;
    console.log(profileImage);
  } 
  else {
    console.log('No File Uploaded...');
    var profileImage = 'noimage.jpg';
  }

  // Form Validator
  req.checkBody('name','Name field is required').notEmpty();
  req.checkBody('title','Title field is required').notEmpty();
  req.checkBody('description','Description is not valid').notEmpty();
  //req.checkBody('profileImage','Please upload an image Jpeg, Png or Gif').isImage(profileImage);

  // Check Errors
  var errors = req.validationErrors();
  console.log(errors);

  if(errors) {
    res.render('login/team/add_team', { errors: errors, title: 'IDID Lab | AdminArea', classname: 'active', page_name: 'view_team' });
  } else {
    const client = new Client({
      connectionString: connectionString,
    });
    client.connect();
    const query = 'INSERT INTO team(team_name, team_title, team_description, team_image, createdby) VALUES($1, $2, $3, $4, $5) RETURNING *'
    const values = [name, title, description, profileImage, created]
    client.query(query, values, (err, result) => {
      if(err) { 
        console.log(err.stack)
      } else {
        req.flash('success', 'Record Added');
        //console.log(message);
        res.location('login/team/view_team');
        res.redirect('login/team/view_team');
      }
      client.end();
  });

我收到以下错误: 无法GET / login / team / view_team

知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

您必须重定向网址,而不是视图的路径。这是documentation

res.redirect(URL);
res.redirect('/teams'); // will show all the teams