AJAX get request problems


#1

I have been trying to get the request from a certain element using Ajax. The problem is that I either get the entire header+body req.get.all() as a request or the object element req.get.raw().

I have been going through the documentation and it has not helped me enough to overpass this issue.

I do not achieve to just receive the data body from the key named “uniqueKey”.

My Ajax call:


    var request = $.ajax({
            url: '/user/autologin',
            type: 'post',
            data: {
              uniqueKey: id
            },
            headers: {
              'x-csrf-token': $('[name=_csrf]').val()
            },
            dataType: 'json'
          });
    
          request.done(function(msg) {
            console.log(msg);
          });
    
          request.fail(function(jqXHR, textStatus) {
            console.log(textStatus, jqXHR);
          });    
        });

My backend controller:


    async autologin({
        request,
        response,
        auth
      }) {
        try {
          await auth.check()
        } catch (error) {
          if (auth.user) return
          const uniqueKey = request.all()
          console.log(error)
          const existingUser = await User.findBy('unique_key', uniqueKey)
          if (existingUser === null) {
            const newUser = new User()
            newUser.unique_key = uniqueKey
            console.log('new user')
            await newUser.save()
            // return await auth.generate(newUser) //jwt
            await auth.login(newUser)
          } else {
            console.log('registered user')
            // return await auth.generate(existingUser) //jwt
            await auth.login(existingUser)
          }
          // return response.send(uniqueKey)
        }
      }

Other unsuccessful tests I have run:

const uniqueKey = request.raw()

const uniqueKey = only(['uniqueKey'])

The data sent through is a string.


#2

There are handful of issues with your code.

  1. What happens when your code never reaches the catch statement. You don’t return anything from the try block?
  2. The request.all() methods returns an object and you have read uniqueKey from that object.

Please learn how to debug your code properly, use console.log statements to see the structure of data.


#3

Hi Virk,

  1. Since this is a function for autologin based on a token stored in local storage. If it reach reaches the try, it means is author if it is not it means is not and therefore that is why I create a new user.

  2. Exactly, that is the logic I want to do, because when I do the Ajax call I am sending the uniqueKey as key. However I still do not understand why it does not work.

I have added logs to trace when it reaches certain part of the method. However, I can not understand why is not very reliable.