Home > Net >  Attempt to get token returns undefined
Attempt to get token returns undefined

Time:05-25

I'm using an API with javascript to make a login and, the login is working, but now, I need to make the logout and I need to get the token from the success message that appears on the console like this:

{"access":1,"message":"Success!","status":200,"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjQyLCJ1c2VybmFtZSI6ImJlcm5hcmRvIiwiYWNjZXNzX21vZGUiOjEsImV4cCI6MTY1MzQ3Mjk0NX0.lf6KgIF7FSjKFhPyRvOplYxgq3DLHEbDiRgHhH_oOWY","uid":42,"username":"bernardo"}

But when I tried to get the token on my fetch like this:

 fetch("https://api.secureme.pt/api/v1/auth/login", requestOptions)
        .then((response) => response.text())
        .then((result) => console.log(result.token)) <-- HERE
        .catch((error) => console.log("error", error));

It returns undefined and I don't know why.

CodePudding user response:

In your code result is a string and what you need is an object.

 fetch("https://api.secureme.pt/api/v1/auth/login", requestOptions)
        .then((response) => response.json()) // parse JSON data
        .then((result) => console.log(result.token))
        .catch((error) => console.log("error", error));
  • Related