Answer the question
In order to leave comments, you need to log in
How to build my node.js+express+mongodb (router, ajax) application?
1) How are ajax requests processed in nodejs in terms of architecture? Those. in express using middleware:
var send_mail = require('./models/send_mail.js');
app.post('/send_mail', function(req,res,next){
send_mail(req.body, new Date());
});
var send = ('./models/send.js');
app.get('/send', function(req,res,next){
res.render('main', data);
});
Answer the question
In order to leave comments, you need to log in
1) Ajax requests are processed in the same way as regular requests. The send_mail function from the example should probably accept a callback:
var send_mail = require('./models/send_mail.js');
app.post('/send_mail', function(req,res){
send_mail(req.body, new Date(), function(err) {
if (err)
res.send({result: false, message: err.message}); // отправляется json
else
res.send({result: true});
});
});
var send = require('./models/send.js');
app.get('/send', function(req,res){
send(function(err, data) {
if (err) throw err; // или как-то по другому обрабатывать
res.render('main', data);
});
});
function send(cb) {
// ... соединение с БД предполагается в переменной db
var collection = db.collection('documents');
collection.find({}).toArray(cb);
}
1) AJAX requests are always and everywhere processed in exactly the same way as regular ones. What is your question - how to distinguish AJAX from non-AJAX? how to send JSON to client?
2) Something like this:
var send = require('./models/send.js');
app.get('/send', function(req, res) {
send(function (err, data) {
if (err) {
return res.send(500, 'Error happened')
} else {
res.render('main', data);
}
})
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question