Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

node.js - Express.js Won't Render in Post Action

Node.js is kinda new, so I hardly can find things in internet. I have already solved this. It was because I was calling from client side using $.ajax. But when I try it in my code below, it never renders. The initial page was /contact, and when I call /contact/sendEmail, all of the function inside /contact/sendEmail are working but not with the render. There was no error at all. It was just like nothing happened.

var Contact = require('../controllers/contact');

module.exports = function(app) {
  app.get('/contact', function(req, res) {
    res.render('contact');
  });
  app.post('/contact/sendEmail', function(req, res, next) {
    var form = req.body;
    Contact.validators.form(form, function(err) {
      if (err) {
        return res.render('user/register'); //This one never works!
        /*return res.render('contact', {
          error: err,
        });*/
      } else {
        Contact.sendEmail(req, res, next);
      }
    });
  });
};

It was called by this function

$('.contact').submit(function(event, done) {
  var form = $(this);
  var data = form.serializeArray();
  // server side validation
  // every contact form field is required
  event.preventDefault();
  $.ajax({
    type: 'POST',
    url: '/contact/sendEmail',
    data: form.serialize()
  })
  .done(function(data) {
    if (data.status == 'OK') {
      $('#contact-success').modal('show');
    } else {
      return done('Please fill all of the fields.', false);
    }
  });
});

For everybody to learn. I changed it to call from server side by adding this to the jade file:

form(role="form" method="POST")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I successfully solved it by myself! I found out that it happened because I call the route from $.ajax from the client. When I change the calling method by putting this code into the form and remove the $.ajax, it's done. Thank you @mscdex

form(role="form" method="POST")

and I changed the route /contact/sendEmail to just /contact.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...