ImranR
ImranR

Reputation: 516

How can I implement Interceptor with this axios code

I am posting to an api using Axios (and Vue.js). I have added a small condition in catch which checks the response data and compares it.

Is there a better way to approach this, as I can imagine this will grow and become harder to maintain. How can I implement interceptor with this example? Ideally I want to handle server error responses better with less code blocks.

axios
          .post("/api/apipathwillgohere", formData)
          .then(function(response) {
            self.sucessfulServerResponse = response.data.message;
            window.localStorage.clear();
            // console.log(response.data);
            if (response.data.success == true) {
              // localStorage.email = response.data.email;
              location.reload();
            } else {
              self.errorMessage = response.data.error;
              self.submitClicked = false;
              console.log(response.data.error);
            }
          })
          .catch(function(error) {
            // If BackEnd refresh flag is true, then refresh page
            if (
              error.response.data.data.refresh == true ||
              error.response.data.data.message == "Token mismatch"
            ) {
              self.submitClicked = true;
              location.reload();
            }

            self.submitClicked = false;
            self.serverError = getErrorMessage(error);

            //helper to get a displayable message to the user
            function getErrorMessage(error) {
              let responseBody;
              responseBody = error.response;
              if (!responseBody) {
                responseBody = error;
              } else {
                responseBody = error.response.data || responseBody;
              }
              return responseBody.message || JSON.stringify(responseBody);
            }
          })
          .then(() => {
            self.status = "";
          });

Upvotes: 0

Views: 119

Answers (1)

MartinT
MartinT

Reputation: 644

If there is a logic you would like to run on every request, you should use an interceptor (check interceptors section in axios documentation. This is especially useful for auth situations, for instance if your api returns token invalid, you should redirect user to login page.

Upvotes: 1

Related Questions