Issue
I'm trying to send a request to my ExpressJS server using AngularJS:
angular.module('app').controller('contactCtrl', function($scope, $http) {
$scope.envoyer = function(nom, organisation, courriel, telephone, message){
$http.post('/contact', {nom:nom, organisation:organisation, courriel:courriel, telephone:telephone, message:message}).then(function(error, response){
if(response.data.success){
console.log('sent!');
}
});
}
});
This is the code from the server:
var mailer = require('nodemailer');
var EMAIL_ACCOUNT_EMAIL = 'aaa@gmail.com';
var EMAIL_ACCOUNT_PASSWORD = 'aaa';
var smtpTransport = mailer.createTransport({
service: "Gmail",
auth: {
user: EMAIL_ACCOUNT_EMAIL,
pass: EMAIL_ACCOUNT_PASSWORD
}
});
app.post('/contact', function(req, res, next){
var success = true;
var mailOptions = {
to: 'azez@email.com',
subject: 'qsdxwccvfd',
html: 'sqdqsdq'
};
smtpTransport.sendMail(mailOptions, function(error, res){
if(error){
console.log('[ERROR] Message NOT sent: ', error);
success = false;
} else {
console.log('[INFO] Message sent: ' + res.message);
}
next(error, success);
});
});
After the server performs the request, I get this error message on the client side:
POST http://localhost:3002/contact 404 (Not Found) angular.js:8495
(anonymous function) angular.js:8495
sendReq angular.js:8291
$http.serverRequest angular.js:8025
wrappedCallback angular.js:11498
wrappedCallback angular.js:11498
(anonymous function) angular.js:11584
Scope.$eval angular.js:12608
Scope.$digest angular.js:12420
Scope.$apply angular.js:12712
(anonymous function) angular.js:18980
jQuery.event.dispatch jquery.js:4409
elemData.handle
I think that it's coming from the fourth line of the AngularJS code, but I wasn't able to find how to fix it. How can I fix that, please?
Solution
In order to send a successful response to the browser, the call to next
at the end of your middleware should be replaced with something like this:
res.set('Content-Type', 'application/json'); // tell Angular that this is JSON
res.send(JSON.stringify({success: success}));
These lines tell express to return a response marked as a success, with a body that is in JSON format with an object that only has the "success" property.
However, in order for this to work you will need to rename the parameter you used in the callback for smtpTransport.sendMail
since you called that res
and so it is currently hiding the res
object from the middleware. So change the header of that function to something like this:
smtpTransport.sendMail(mailOptions, function(error, mailRes){
...and then of course you must change the log line that follows to use mailRes
instead of res
.
Answered By - Martin Atkins
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.