问题
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")
回答1:
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
.
来源:https://stackoverflow.com/questions/26301254/express-js-wont-render-in-post-action