Detailed explanation of the use of vue-resource interceptors

Detailed explanation of the use of vue-resource interceptors

Preface

Interceptor

In some modern front-end frameworks, interceptors are basically a very basic but very important part. For example, Angular natively supports interceptor configuration, and VUE's Axios module also provides us with interceptor configuration. So what exactly is an interceptor and what is its use?

Interceptors can help us solve

  • Add unified request parameters
  • For example, add X-Requested-With to the header, or the client needs to implement the sign and token verification mechanism. For example, you can write $http.get('/files', params), and the interceptor will help you splice it into a request address like http://www.xxxx.com/1/files.
  • Handling unified responseError
  • For example, the reconnection mechanism gets the error code and reconnects. For example, if the token expires, get the token again and send the request again.
  • For example, it would be cool to unify the error message and give a prompt for all 404 returned

In the process of using vue-resource to implement asynchronous loading in the vue project, it is necessary to add a check for token expiration during any http request on any page. If the token has expired, it is necessary to jump to the login page. If you want to add a judgment in the http request operation of each page, it will be a very large modification workload. So does vue-resource have a public callback function that captures any request response? The answer is yes!

The role of vue-resource's interceptors is exactly the solution to this requirement. After each http request response, if an interceptor is set, the interceptor function will be executed first to obtain the response body, and then decide whether to return the response to then for reception. Then we can add a judgment on the response status code in this interceptor to decide whether to jump to the login page or stay on the current page to continue to obtain data.

Installation and Reference

NPM: npm install vue-resource --save-dev

/*Introduce Vue framework*/
import Vue from 'vue'
/*Introduce resource request plugin*/
import VueResource from 'vue-resource'

/*Use VueResource plugin*/
Vue.use(VueResource)

Add the following code to main.js

Vue.http.interceptors.push((request, next) => {
 console.log(this) //This is the Vue instance of the requested page // modify request
 request.method = 'POST'; //Some preprocessing and configuration can be done before the request // continue to next interceptor
  next((response) => {//After the response, modify and make logical judgments on the response before passing it to then. For the judgment that the token has expired, add it here. Any http request in the page will first call this method response.body = '...';
    return response;

 });
});

Interceptor Example

(1) Add loading effect to the request

Through the inteceptor, we can add a loading screen for all request processing: display the loading screen before sending the request and hide the loading screen after receiving the response.
The specific steps are as follows:

//1. Add a loading component <template id='loading-template'>
  <div class='loading-overlay'></div>
</template>

//2. Use the loading component as a subcomponent of another Vue instance var help = new Vue({
  el: '#help',
  data: {
    showLoading: false
  },
  components:
    'loading': {
      template: '#loading-template',
    }
  }
})

//3. Mount the Vue instance to an HTML element <div id='help'>
  <loading v-show='showLoading'></loading>
</div>

//4. Add inteceptor
Vue.http.interceptors.push((request, next) => {
  loading.show = true;
  next((response) => {
    loading.show = false;
    return response;
  });
});

However, when the user stays on the screen for too long, the view data may no longer be the latest. At this time, if the user deletes or modifies a piece of data, if this data has been deleted by other users, the server will feedback a 404 error. However, since our put and delete requests do not handle errorCallback, the user does not know whether his operation is successful or failed. This problem can also be solved by inteceptor.

(2) Add a common error handling method for requests

//1. Continue to use the above loading component and add a dialog box <div id='help'> under the #help element
  <loading v-show='showLoading' ></loading>
  <modal-dialog :show='showDialog'>
    <header class='dialog-header' slot='header'>
      <h3 class='dialog-title'>Server Error</h3>
    </header>
    <div class='dialog-body' slot='body'>
      <p class='error'>Oops, server has got some errors, error code: {{errorCode}}.</p>
    </div>
  </modal-dialog>
</div>

//2. Add two properties to the data option of the help instance var help = new Vue({
    el: '#help',
    data: {
      showLoading: false,
      showDialog: false,
      errorCode: ''
    },
    components:
      'loading': {
        template: '#loading-template',
      }
    }
  })

//3. Modify inteceptor
Vue.http.interceptors.push((request, next) => {
  help.showLoading = true;
  next((response) => {
    if(!response.ok){
      help.errorCode = response.status;
      help.showDialog = true;
    }
    help.showLoading = false;
    return response;
  });
});

This is the end of this article about the detailed use of vue-resource interceptors. For more relevant vue-resource interceptor content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue adds request interceptor and vue-resource interceptor usage
  • Example of vue-resource interceptor setting header information
  • An example of Vue-resource interceptor judging token invalid jump
  • Detailed explanation of the use of vue-resource interceptor
  • Detailed explanation of the use of vue-resource interceptor

<<:  How to configure MySQL on Ubuntu 16.04 server and enable remote connection

>>:  MySQL 5.7.17 installation and configuration method graphic tutorial (windows)

Recommend

Do you know what are the ways to jump routes in Vue?

Table of contents The first method: router-link (...

Detailed explanation of HTML table inline format

Inline format <colgroup>...</colgroup>...

Detailed explanation of mysql partition function and example analysis

First, what is database partitioning? I wrote an ...

jQuery manipulates cookies

Copy code The code is as follows: jQuery.cookie =...

7 cool dynamic website designs for inspiration

In the field of design, there are different desig...

MySQL 8.0.25 installation and configuration method graphic tutorial

The latest download and installation tutorial of ...

Detailed explanation of Vue's monitoring properties

Table of contents Vue monitor properties What is ...

Create a virtual environment using venv in python3 in Ubuntu

1. Virtual environment follows the project, creat...

Hide HTML elements through display or visibility

Sometimes we need to control whether HTML elements...

Linux gzip command compression file implementation principle and code examples

gzip is a command often used in Linux systems to ...

JavaScript to implement retractable secondary menu

The specific code for implementing the retractabl...

Detailed tutorial on installing mysql under Linux

1. Shut down the mysql service # service mysqld s...