Question

I am looking for a callback to use in my $save method in angularjs.

I am sending a blog post to the node.js backend, passing it through the recaptcha verifying.

Doing as in the $resource documentation is not working:

non-GET instance actions: instance.$action([parameters], [success], [error])

var post = new Posts({
            title: this.title,
            content: this.content,
            response: this.model.captcha.response,
            challenge: this.model.captcha.challenge
         });

post.$save({}, 
     function(addedpost) {
         $location.path('posts/' + addedpost._id);
    }, function(error) {
         console.log(error);
         vcRecaptchaService.reload();
    });

In the server I am using the simple_recaptcha module for node.js to verify the recaptcha challenge and response that is packed within the request.

var verifyRecaptcha = function(req,res,next){
    var privateKey = 'XXXXXXXXXXXXXXXXXXXXXXXX';
    var ip = req.ip;
    var challenge = req.body.challenge;
    var response = req.body.response;
    simple_recaptcha(privateKey, ip, challenge, response, function(err) {
        if(err) return res.send(401,err.message);
        console.log('Recaptcha verified!');
    });
    next();
};

So when the captcha is correct it should continue and add the post to the db, if not, the backend responds 401 and the frontend angular js should recognise this as error and refresh the recaptcha.

What am I missing?

Was it helpful?

Solution

Sometimes I get lost as well in the (normally very good) documentation of AngularJS. In my case, I found a solution here: how-to-add-call-back-for-resource-methods-in-angularjs

You can let the server do its work on the POST and analyse the response, something like:

    post.$save(
        function(data){
            console.log(JSON.stringify(data));
            if(data.error_message){
                 // ... error_message comes from the server
            } else {
                // ...
            }
        }
    );        
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top