1

My current problem, is how to redirect signup route to homepage route with the token. The backend of this route does create the token, but for the frontend I couldn't figure out of how to do it.

.controller('UserCreateController', function(User, $location, $localStorage) {

var vm = this;


// function to create a user
vm.SignUpUser = function() {
    vm.processing = true;

    // clear the message
    vm.message = '';

    // use the create function in the userService
    User.create(vm.userData)
        .success(function(data) {
            vm.processing = false;

            // clear the form
            vm.userData = {};
            vm.message = data.message;

              // What should i do here to get the token?
              $location.path('/')

    });

};

})

service.js

userFactory.create = function(userData) {

        return $http.post('/api/signup', userData);

    }

This is the service, and how do i return it with the token

Updated version: This is my Api in node/express of generating the token after the user has signup

api.js

var createToken = function(user) {

    var token = jwt.sign({
        id: user._id,
        name: user.name,
        username: user.username
    }, superSecret, {
        expiresInMinute: 1440
    });

    return token;

}





    apiRouter.post('/signup', function(req, res) {

            var user = new User({
                name: req.body.name,
                username: req.body.username,
                password: req.body.password
            });

            var token = createToken(user);
            user.save(function(err) {
                if(err) { 
                    res.send(err);
                    return;
                }

                res.json({
                    success: true, 
                    message: 'User has been created!',
                    token: token
                });
            });

I have no clue of how to pass that json data that has been generated by the api to the angular.

airsoftFreak
  • 1,450
  • 5
  • 34
  • 64
  • What is this token, and what is it used for? Is it generated by the signup process? Can you not return it from the server call, and just access it as `data.token`? – Mike Chamberlain Feb 01 '15 at 07:44
  • @MikeChamberlain I'm really confused with the angular thing, sorry if I made any mistake. Anyway the token is generated by the signup process and the token holds the information of the user. Check my updated version – airsoftFreak Feb 01 '15 at 07:53

2 Answers2

2

First, you need to retrieve the token from response headers, so update your service to:

userFactory.create = function(userData) {
    return $http.post('/api/signup', userData)
        .then(function(data, status, headers, config, status) {
           return data;
        });
}

Then you can read the token from controller

User.create(vm.userData)
    .then(function(data) {
        vm.processing = false;

        vm.userData = {};
        vm.message = data.message;

        // remember to reference $window in your controller
        $window.localStorage.setItem('token', data.token);
        $location.path('/')

});

After users login or signup, next time when you send requests to backend, you can add token to headers manually.

var req = {
 method: 'POST',
 url: 'http://example.com',
 headers: {
   'Authentication': $window.localStorage.getItem('token')
 },
 data: { test: 'test' },
}

$http(req).success(function(){...}).error(function(){...});
Rebornix
  • 5,272
  • 1
  • 23
  • 26
  • Thank you so much for your help, but last question though where do you put the last section of the code? and Do i need to implement it on service? I'm sorry for asking so many questions since I'm not really understand angular that muc – airsoftFreak Feb 02 '15 at 02:31
  • No problem. You can put it in any place where you use `$http`. In your case, you may want to add my code in the service.js. – Rebornix Feb 02 '15 at 02:35
  • last thing check my gist for a while https://gist.github.com/anonymous/20e0beec2b58b8937492 after I have implemented your last code, the controller spits out a new error saying that .then is an undefined function. Lastly how bout the interceptor? – airsoftFreak Feb 02 '15 at 02:39
  • See my comment after the gist. – Rebornix Feb 02 '15 at 02:51
  • It appears that the previous problem occurs again, where the token is undefined. I'm really really sorry if I'm bothering you too much again .. – airsoftFreak Feb 02 '15 at 02:54
  • Can you create a sample app in http://plnkr.co/ or http://jsfiddle.net/ then I can debug your code directly, it would be easier than commenting in gist. – Rebornix Feb 02 '15 at 03:18
  • Here you go http://embed.plnkr.co/rwQi13baCFvrDUoWWjPL/preview If you want me to add the server.js and api.js let me know. – airsoftFreak Feb 02 '15 at 03:34
  • Is it possible that you can run your nodejs app in cloud or make your node service accessible in public? – Rebornix Feb 02 '15 at 03:46
  • Before that, you can try to use `$cookies` as Proof of concept, then we can know where the problem locates: localStorage or others. – Rebornix Feb 02 '15 at 03:48
  • Hey check out the link, https://user-testing2015.herokuapp.com , Try to sign up. and check the source code just in case https://github.com/kacak9229/user – airsoftFreak Feb 02 '15 at 04:31
  • @airsoftFreak I sent you a pull request with comments. – Rebornix Feb 02 '15 at 05:42
  • Could you check https://user-testing2015.herokuapp.com/ and check out the console. I just merge your pull request, seems like theres an error and I tried to fix it and run it locally and the problem persist – airsoftFreak Feb 02 '15 at 06:00
  • Since I didn't run it locally, I made a typo in storyService. Try deploy to heroku again. – Rebornix Feb 02 '15 at 06:05
  • You fixed another problem that I'm getting such as, after login the username on the navbar doesnt show up only after I refresh the page they showup. After your update it kinda fixed the problem. Anyway, the signup problem still persist , it doesnt pass the token that the node has created to the angular. – airsoftFreak Feb 02 '15 at 06:22
  • If you check my api middleware, in order for a user to go to a certain route the user's token has to be verified first. Then it will grant access. Basically I'm just wondering what actualy did you fix? please explain to me I'm really clueless XD. Ignore my above comment since that problem still persist , I will open a discussion for that specific question – airsoftFreak Feb 02 '15 at 06:26
  • @airsoftFreak check my latest pr, I suppose after merging this pr, the token problem should be solved. – Rebornix Feb 02 '15 at 06:30
  • My bad , It does solve the problem T_T after exchanging so many comments. Thank you so much Rebornix !!, could you please explain why it behaves that way? – airsoftFreak Feb 02 '15 at 06:43
  • for example when you changed the promise object from data to response.. whats the difference? – airsoftFreak Feb 02 '15 at 06:49
  • A big difference is that the then callbacks take a single argument--the response--while success and error take individual components of the response as arguments--data, status, header, and config. You can refer to [this](http://stackoverflow.com/questions/16385278/angular-httppromise-difference-between-success-error-methods-and-thens-a) to know more details. – Rebornix Feb 02 '15 at 06:56
  • One more small tip for you: always add `;` after declaring a function or variable. – Rebornix Feb 02 '15 at 06:57
  • Noted!! and you are really awesome for spending your time to help me out! :) I have another question that no one has ever solved it yet, its a new question maybe you could check it out since you know most of my codes http://stackoverflow.com/questions/28264255/having-trouble-on-rendering-data-to-angular – airsoftFreak Feb 02 '15 at 07:09
  • @airsoftFreak I have commented on that question. – Rebornix Feb 02 '15 at 08:25
  • I have added a new question regarding angular and caching http://stackoverflow.com/questions/28335583/caching-with-angularjs – airsoftFreak Feb 05 '15 at 03:17
0

The code you posted looks good. If you return this token as part of the JSON result from your server API call, you should be able to access it as a property on the data variable in your success method.

Using the network tab of the developer tools in Chrome (F12), what do you see returned from the server when you call /api/signup? Do you see the token there?

Mike Chamberlain
  • 39,692
  • 27
  • 110
  • 158
  • The only problem right now, is to get the token that has been generated by the api and pass it to the angular, and I'm returning the token in a JSON format. – airsoftFreak Feb 01 '15 at 08:10
  • So what's the actual problem? Does your server response body contain the token or not? If so, you should have access to it on the data object. If not, then you need to return it from your server. – Mike Chamberlain Feb 01 '15 at 09:39
  • Sorry for the late reply , if you know node/express i just updated my question with the api code. – airsoftFreak Feb 01 '15 at 11:36
  • What are you seeing returned by the API call in the Network tab of the Chrome developer tools or Firebug? – Mike Chamberlain Feb 01 '15 at 22:22