Express res.render called by app.post

Inside the Express Application Generator stub I created a new view called test

.

I cannot call test

using:

app.post('/test', function(req, res, next) {
    res.render('test');
});

      

Seems awesome because app.get

below gets rendered as expected:

app.get('/test', function(req, res, next) {
    res.render('test');
});

      

I've also tried the following, but it still doesn't display the page:

app.post('/test', function(req, res, next) {
    console.log('within app.post'); // this is getting logged
    res.redirect('/test');
});

      

Please, help. How to render test

from a post method?

+3


source to share


3 answers


So there is probably a problem with the javascript code. I add the code below to the index.js file in the routes folder and the template does the rendering:

router.get('/test', function(req, res, next) {
    res.render('index', {title: 'GET test'});
});

router.post('/test', function(req, res, next) {
    res.render('index', {title: 'POST test'});
});

      

Try sending a request via curl:



curl -v -XPOST http://localhost:3000/test

      

Or use chrome or firefox extension to fulfill the request.

+3


source


It looks like you are confused with redirect

and render

as far as I know you need one router method that will render the page you want and whenever you want to get land on that page you can use a call redirect

, For example,



// This will render the index.html page
app.get('/login', function(req,res) {
  res.render('index.html');
});

// This will redirect to above page
app.post('/homepage', function(req,res) {
  res.redirect('/login');
});

      

0


source


I don't know if this is the best way to do it, but you really want your render to be in the same place for each route. I am using .all () to handle the display of the page regardless of whether something was submitted.

app.post('/test', function(req, res, next) {
  // Do something with posted data
  next();
})
app.all('/test', function(req, res) {
  // res.render the page
});

      

0


source







All Articles