Johhan Johhan - 6 days ago 5
AngularJS Question

AngularJS $http ".then" callback is not firing with ExpressJS and sendgrid

I have this function in angular

controller: function ($scope, $http) {
$scope.sendEMail = function (referal) {
// console.log('referal: ', referal);

$http({
url: '/send-referal',
method: "POST",
data: referal
}).then(function (response) {
console.log('success', response);
},
function (response) { // optional
console.log('error', response);
});
};
}


Now the
.then
is not executing after.

In the server side in express I have the endpoint like this:

app.post('/send-referal', function (req, res) {
console.log('data: ', req.body);

var html = "my html template";

var helper = require('sendgrid').mail;
var from_email = new helper.Email(req.body.email);
var to_email = new helper.Email('foo@bar.com');
var subject = 'Subject for referal form';
var content = new helper.Content('text/html', html);
var mail = new helper.Mail(from_email, subject, to_email, content);

var sg = require('sendgrid')('api key here');
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON(),
});

sg.API(request, function(error, response) {
console.log(response.statusCode);
console.log(response.body);
console.log(response.headers);
});
});


This is the normal example that sendgrid gives you. The function sends the email normally but in client side I don't get any response at all so I could tell the user that the email was sent.

How do I get the
$http
request to fire the
.then
action?

Answer

You have to send the response back from the server with res.json as below,

app.post('/send-referal', function (req, res) {
  console.log('data: ', req.body);

  var html = "my html template";

  var helper = require('sendgrid').mail;
  var from_email = new helper.Email(req.body.email);
  var to_email = new helper.Email('foo@bar.com');
  var subject = 'Subject for referal form';
  var content = new helper.Content('text/html', html);
  var mail = new helper.Mail(from_email, subject, to_email, content);

  var sg = require('sendgrid')('api key here');
  var request = sg.emptyRequest({
    method: 'POST',
    path: '/v3/mail/send',
    body: mail.toJSON(),
  });

  sg.API(request, function(error, response) {
    console.log(response.statusCode);
    console.log(response.body);
    console.log(response.headers);
  });

  // Send the response back to client something like below
  res.json({success:true});
});
Comments