1

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

hrivera
  • 13
  • 5

1 Answers1

1

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

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • Oops! :) Hadn't seen that missing parameter. This took care of the missing data. However now the method saveToken (also declared in the service) is throwing not defined. This is probably because I'm inside a callback and using 'this' doesn't reference the service anymore. I need to save the token that is returned from the server to localstorage (this is what saveToken does). Any recommendation on how to do this. – hrivera Nov 22 '16 at 20:25
  • @hrivera because `this` inside a function isn't a this which you are thinking.. I'd highly recommend to go through [this article](http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/) – Pankaj Parkar Nov 22 '16 at 20:27
  • Thanks, will look into it – hrivera Nov 22 '16 at 20:45