это вопрос новичков по правильному использованию узла-mandrill и, скорее всего, на самом узле, поскольку я все еще пытаюсь его изучить. Но так как я видел много примеров, чтобы использовать ключ api из мандрилла непосредственно с клиентской стороны и, следовательно, раскрывая его, мне было интересно, как именно он работал, когда он служил, но застрял в этом пункте:
У меня есть app.js, обслуживающий общую папку...
app.js
var express = require('express');
var mandrill = require('node-mandrill')(API_KEY);
var app = express();
app.use(express.static('public'));
app.listen(PORT);
function sendEmail ( _name, _email, _subject, _message) {
mandrill('/messages/send', {
message: {
to: 'EMAIL',
from: [{email: _email , name: _name}],
subject: _subject,
text: _message
}
}, function(error, response){
if (error) console.log( error );
else console.log(response);
});
}
... где клиентский скрипт используется для сбора информации из контактной формы и отправки электронной почты при нажатии кнопки отправки.
form.js
var contactForm = document.getElementById( 'contactForm' );
new stepsForm( contactForm, {
onSubmit : function( form ) {
// send email
var _subject = 'Contact Request';
var _email = contactForm.elements['q4'].value;
var _name = contactForm.elements['q5'].value;
var _message = contactForm.elements['q6'].value;
sendEmail(_name,_email,_subject,_message);
}
} );
Не могли бы вы рассказать мне, что пропало/не так? Благодарю.
Вы не можете вызывать функцию back-end от клиента. Вы можете использовать Jquery для вызова Ajax, например:
$(document).ready(function(){
$('#contactForm').submit(function(event) {
event.preventDefault();
var _subject = 'Contact Request';
var _email = contactForm.elements['q4'].value;
var _name = contactForm.elements['q5'].value;
var _message = contactForm.elements['q6'].value;
$.ajax({
url: '/sendEmail',
method: 'post',
contentType: 'application/json',
data: JSON.stringify({ subject: _subject, email: _email}),
success: function(res) {
}
})
})
})
И в вашем back-end:
// some lines skipped
app.post('/sendEmail', function(req, res) {
//do your stuff
})
POST http://.../sendEmail 404 (Not Found)
. Это то, что я добавил вapp.post('/sendEmail',function(res,req){ mandrill('/messages/send', { message: { to: '[email protected]', from: [{email: req.email , name: req.name}], subject: req.subject, text: req.message } }, function(error, response){ if (error) console.log( error ); else console.log(response); }); });
:app.post('/sendEmail',function(res,req){ mandrill('/messages/send', { message: { to: '[email protected]', from: [{email: req.email , name: req.name}], subject: req.subject, text: req.message } }, function(error, response){ if (error) console.log( error ); else console.log(response); }); });