问题
I am working on a CRUD app in Nodejs/Expressjs with EJS as a templating engine.
I created a folder in my "views" folder, name login in which I have few files. Views folder contains all my .ejs files. Now after successful insertion (via a router), I want to redirect to an .ejs file (login/filename). But it is not working.
Here is my working directory:
I have added all relevant routers.
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'));
});
(router)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();
});
The following error I am getting: Cannot GET /login/team/view_team
Any idea how to solve this issue?
回答1:
You have to redirect on an url not the path of the view. Here is the documentation.
res.redirect(URL);
res.redirect('/teams'); // will show all the teams
来源:https://stackoverflow.com/questions/46910837/nodejs-expressjs-redirect-after-successful-insertion