0

I have a authentication API that response a token when i make a login request(http://localhost:3001/api/users/login).

//Login
router.post('/login', async (req, res) => {
    //Validate data before we use
    const { error } = loginValidation(req.body);
    if (error) return res.status(400).send(error.details[0].message)
    //Checking if the email exists
    const user = await User.findOne({
        email: req.body.email
    })
    if (!user) return res.status(400).send('Email or password dont match')
    //Password is correct 
    const validPass = await bcrypt.compare(req.body.password, user.password)
    if (!validPass) return res.status(400).send('Invalid password')

    //Create and assign a token

    const token = jwt.sign({ _id: user._id }, process.env.TOKEN_SECRET);
    res.header('auth-token', token).send(token)

})

I want to take that data from const token in my front end in local storage using Jquery. So i register my user.

   $('#button-click').click(function () {
        $.ajax(
            {
                type: "POST",
                url: 'http://localhost:3001/api/user/register',
                data: JSON.stringify({
                    "name": $("#name").val(),
                    "email": $("#email").val(),
                    "password": $("#password").val()
                }),
                error: function (e) {
                    console.log(e)
                },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
            }

        )

    })

but i dont know how to take that data, can anyone help me ?

3 Answers3

1

You can provide a success function the same way you provided an error function. This function will be called when the request was successful.

$.ajax({
    ...,
    success: function(data, status, jqXHR) {
    //do stuff with data
    },
    ...
});

Source: https://api.jquery.com/jquery.ajax/

  • so, my data gonna be stored in function(data){ console.log(data.token) }? The variable name is 'token' – Vitor Ramalho Nov 19 '19 at 18:55
  • The variable name on your server-side doesn't matter in this case. The complete data you send is stored in data. You only send the token, so data is your token – Drachenfrucht1 Nov 20 '19 at 11:58
0

Success is used to handle the response from the api

      $.ajax({
                type: "POST",
                dataType: "json",
                url: "http://localhost:8080/api/user",
                data: {},
                contentType: "application/json; charset=utf-8",
                dataType: "json", 
                success: function (data, status, jqXHR) {
                    alert(data);
                    localStorage.setItem('token', data);
                },
                error: function (error) {

                    jsonValue = jQuery.parseJSON(error.responseText);
                    alert("error" + error.responseText);
                }
            });

For more details - https://api.jquery.com/jQuery.ajax/

More details on localstorage - https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

hope it helps :)

Samarth Saxena
  • 1,121
  • 11
  • 18
  • @Vitor Updated my answer for bad request try adding contentType and datatype. Be sure that the data is in json format – Samarth Saxena Nov 19 '19 at 18:55
  • what if i want to store the data and note alert him? – Vitor Ramalho Nov 19 '19 at 18:56
  • it depends where you want to store the data and whatever operations you want to perform you can do that inside success function note , alert , store etc. That function will execute after the success response from the server. I am changing my function to store the token in local storage for help – Samarth Saxena Nov 19 '19 at 19:01
0

Just add success event and store the response token in localstorage and use the token in the way you want.

$('#button-click').click(function () {
        $.ajax(
            {
                type: "POST",
                url: 'http://localhost:3001/api/user/register',
                data: JSON.stringify({
                    "name": $("#name").val(),
                    "email": $("#email").val(),
                    "password": $("#password").val()
                }),
                error: function (e) {
                    console.log(e)
                },
                contentType: "application/json; charset=utf-8",
                dataType: "json",

                success: function(data, status, jqXHR) {
                       localStorage.setItem("app_token", data.token);
                },
            }

        )

    })
Nouman Janjua
  • 410
  • 2
  • 9