How to store a JWT Token in a simple method and redirect to another page?

Asked

Viewed 163 times

0

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Title</title>
</head>
<body>
<form>
  <input type="email" name="email" placeholder="email">
  <button type="button" id="send">enviar</button>
</form>

<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>

<script type="text/javascript">
  $('#send').on('click', function(){
    $.ajax({
      url: "URL QUE RETORNA O TOKEN",
      method: "post",
      contentType: "application/json",
      data: '{ "email": "[email protected]" }',
      success: function (data) {
        console.log(data);
     }
    });
  });
</script>
</body>
</html>

NOTE: console.log(data); ME RETURNS THE TOKEN PERFECTLY

  • I agree, but it can be as simple as possible (a variable for example), for testing purposes.

  • You can suggest a method that the token does not get lost in a variable?

1 answer

1


Store the return in a cookie:

localStorage.setItem("token", data);

and redirect:

location.href = "pagina.html";

On the redirected page, retrieve the value stored in the cookie:

localStorage.getItem("token");
  • Thanks for the suggestion, I’ll run the tests.

  • Good luck! It’ll be fine.

  • Hello, I used your suggested code, I got the following return message "Content Security Policy: Page settings blocked loading a resource in "1URL" ("default-src")." The token must be sent by the GET method to URL /feed, structure : Curl "URL /feed" -H "Authorization: $TOKEN" -H "Content-Type: application/json" I tried to store the token in a var, I was able to know the syntax and even with examples from W3schools the error persisted. I created a second function with POST method that uses your getItem. I call the 2nd in the 1st Function in the last line. Forgiveness for mistakes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.