Search code examples
angularjsnode.jsangular-resource

data is undefined in transformRequest using $resource


I'm working on a small project with MEAN in order to get started with it. I've been following the tutorial on thinkster.io (with some minor modifications made by me) and so far I've obtained good results. I've tested the API routes with Postman and everything is working. Problem is, for some reason (keep in mind that I'm new to NodeJS), it only accepts requests with Content-type: x-www-form-urlencoded.

The solution I've come across several times is to change the headers in the options parameter of the $resource. This is the code I have

register: function(user){

        var deferred = $q.defer();
        var UserResource = $resource('/api/users/register', {}, {
            save: {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                transformRequest: function (data, headersGetter) {
                    console.log(data); // data is undefined ??
                    var str = [];
                    for (var d in data)
                       str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));

                    return str.join("&");
               }
            }
        });

        UserResource.save(function(user){
            this.saveToken(user.token);
            deferred.resolve(user);
        }, function(user){              
            deferred.reject(user);
        });
        return deferred.promise;
}

The register function is declared on an angular service. Problem is that the backend is sending me an error because the req.body object is empty. This is due to the fact that the transformRequest method is not executing correctly. Doing a little debugging I found that the 'data' parameter is undefined. This is the code in the backend

router.post('/register', function(req, res, next){          
    if(!req.body.username || !req.body.password){
        console.log(req.body.username);
        return res.status(400).json({message: 'Por favor llene todos los campos'});
    }

    var user = new User();

    user.username = req.body.username;

    user.fullname = req.body.fullname;

    user.setPassword(req.body.password);

    user.save(function (err){
        if(err){ return next(err); }

        return res.json({token: user.generateJWT()})
    });
});

Any ideas would be appreciated. Thanks in advance


Solution

  • You should pass user data in 1st parameter of save method(that will pass through the request body), there after you can place successCallback & errorCallback

    UserResource.save(user, function(user){
        this.saveToken(user.token);
        deferred.resolve(user);
    }, function(user){              
        deferred.reject(user);
    });
    

    Checkout this article