Sending the Token to the Front-end in MEAN Stack
In our previous section, we successfully created the JSON Web Token. In this section, we will learn how we will send this web token to our front-end. The question is that how we will return that token. For this, we will use the following steps:
1) We will create a new response and set the status code to 200 because here we did successfully authenticate, and we will send a JSON response where we can send a message but, most importantly, where we will set our token. So, there we will return the token, which we have generated previously.
2) The backend is finished and move on to the front-end. In the auth.service.ts file, we will create a new method loginUser(). There, we definitely need an email and a password because we need data to send to the backend. And then we will again send a post request 0 and we will send a post request to that same URL well almost, the end will be /login to target that newly created route but we will also create our auth data just like for signing up and append out AuthData like this:
3) Now, we need to subscribe to it, and for that, we simple console log the response to see what is inside of it. We should see the token there for valid credentials.
4) Now, we need to connect that newly connected service method to the login component, and for that in the login component, we will again inject our authservice of type AuthService. We need to add the import to that at the top like this:
5) Now, in our onLogin() method, we will check for the case in which our form is invalid. So, if our form is invalid, we will simply add the return statement. Otherwise, we will send that request by calling the loginUser() method of our authservice. We pass the email and password value to that function like this:
If we try to login after signup, it will throw an error, i.e., "user1 is not defined".
6) In order to solve this, we will go back to our user.js file, and there we use the user1 variable, and that is not in the scope of the 2nd then block. So, we will create another variable, i.e., fetcheduser and assign the user1 value so that it will be accessible in the 2nd then block.
Now, if we go back to our application and try to log in, we will see the token in the developer console.
In the next section, we will store that token in our front-end code and then use it to authenticate for future requests to protect routes.