0
votes

I've just managed to get my $http post working over Angular. It does what it needs to do, but when I post the data and then refresh the page it gives this error in my console:

Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/insert","data":

This is my Angular post call:

app.controller('ContactCtrl', function($scope, $http){
  $scope.formModel = {};
  $scope.onSubmit = function(){
  $http.post('/insert', $scope.formModel)
  console.log('success');
  };
});

And this is my server call in Express.js to my MongoDB:

router.post('/insert', function(req, res, next){
  var item = {
    name: req.body.name,
    adress: req.body.adress,
    postal: req.body.postal,
    city: req.body.city,
    email: req.body.email,
    phone: req.body.phone,
    quotation: req.body.quotation,
    message: req.body.message
};

var data = new UserData(item);
data.save();
console.log('Item inserted');

});
1
status":-1" means possibly network issue..check the mongodb connection. also please tell $scope.formModel object - diEcho
That seems not to be the issue because my data is successfully stored in the db - Larsmanson
then you did not send back the status 200 after .save() just like res.json(testObject); - diEcho
Yes, the status 200 did the trick. Thank you :) - Larsmanson

1 Answers

2
votes

try with

var BACKEND_URL = "http://whatever:port";
var postData = angular.toJson($scope.formModel, true);
$http.post(BACKEND_URL + '/insert', postData);

and on the backend, either use res.sendStatus(200); after mongo save operation or modify like below.

.save(function(err, result) {
    if (err) throw err;

    if(result) {
        res.json(result)
    }
})