Home > Software design >  Vuejs Jwt Token Authentication
Vuejs Jwt Token Authentication

Time:12-04

I want to use Jwt token in my project. So I'm using this function after every api request;

function handleResponse(response) {
    return response.text().then(text => {
        if (response.status == 401) {
            var user = JSON.parse(localStorage.getItem('user'))
            if (user && user.tokens) {
                tokenService.refresh()
                console.log(response);
                return Api(response.url)
            }
        }
        const data = text && JSON.parse(text);
        return data;
    });
}

Token service is refreshing successfully but after refresh I want to send last request again. I can get url but I can't get sended body credentials. How can I do that?

CodePudding user response:

If you want to send the same request again after you refresh the token, you can store the request details (e.g., URL, method, body, headers) in a variable before you refresh the token, and then use that information to make the request again after the token has been refreshed.

Here's an example of how you could do this:

function handleResponse(response) {
  return response.text().then(text => {
    if (response.status == 401) {
      var user = JSON.parse(localStorage.getItem('user'))
      if (user && user.tokens) {
        // Store the request details in a variable.
        const requestDetails = {
          url: response.url,
          method: response.method,
          body: response.body,
          headers: response.headers,
        };

        tokenService.refresh()
          .then(() => {
            // Make the request again using the stored request details.
            return Api(requestDetails.url, {
              method: requestDetails.method,
              body: requestDetails.body,
              headers: requestDetails.headers,
            });
          });
      }
    }
    const data = text && JSON.parse(text);
    return data;
  });
}

In the example above, after the token is refreshed, the request is made again using the same details as the original request. This will ensure that the request is sent with the updated token.

  • Related