Request interceptors and response interceptors in Vue

Keywords: Javascript Vue Vue.js Ajax

Front

Hello everyone, I'm here again. Today we'll talk about what is a request interceptor and the role of a request interceptor. Well, I won't say anything superfluous. I'll start today's explanation right away

Here we go

request interceptor

The function of the request interceptor is to:

Some operations are performed before the request is sent. For example, a token is added to each request body, which is processed uniformly. It is also very easy to change it.

About interception

Here we only talk about the principle. The front-end request is ultimately inseparable from Ajax. For example, Vue resource and Axios of Vue only encapsulate Ajax uniformly. The interceptor exposed by Vue actually writes a method to write Ajax in this method (let's talk about the request interceptor first). When executing the request, first add the data to the request header (Token, the encrypted password to be used at the back end) execute it first, assign it to a variable, and then pass it to Ajax. Next, execute Ajax, which is the so-called request interceptor. In fact, it executes the data to be added first, and then executes Ajax. If you extract the process of adding data, it becomes the so-called request interceptor

// Request timeout
axios.defaults.timeout = 120000

// Add request interceptor
axios.interceptors.request.use(
  config => {
    // What to do before sending the request
    // Judge whether there is a token. If so, add a token to each page header
    if (window.sessionStorage.getItem('DT')) {
      // Request header configuration global token
      config.headers.DT = window.sessionStorage.getItem('DT')
    }
    return config
  },
  err => {
    // What to do about request errors
    Vue.prototype.$message.error('request timeout')
    return Promise.reject(err)
  }
)

Response interceptor

The function of the response interceptor is

After receiving the response, perform some operations. For example, when the login status returned by the server fails, you need to log in again and jump to the login page,
The response interceptor does not export the request result directly, but processes the response code first, and then exports it to the page. If the processing process of the object response code is extracted, it becomes the so-called response interceptor
The code is as follows

// Response interceptor
axios.interceptors.response.use(
  response => {
    // res is the result of the response
    switch (response.data.code) {
      case 401:
        // Login failure
        // Response to successful interception
        console.log('Response Interceptor:')
        // console.log(response.data)
        Vue.prototype.$message.error(response.data.message)
        sessionStorage.removeItem('DT')
        router.push('/login')
        break
      case 404:
        if (response.data.message !== null) {
          Vue.prototype.$message.error(response.data.message)
        } else {
          Vue.prototype.$message.error('unknown error')
        }
        break
      case 500:
        // error
        if (response.data.message !== null) {
          Vue.prototype.$message.error(response.data.message)
        } else {
          Vue.prototype.$message.error('unknown error')
        }
        break
      default:
        return response
    }
    return response
  },
  err => {
    if (err.response.data.message) {
      Vue.prototype.$message.error(err.response.data.message)
      return Promise.reject(err.response.data.message) // Returns the error information returned by the interface
    } else {
      // Error handling when the return status code is not 200
      Vue.prototype.$message.error(err.toString())
      return Promise.resolve(err)
    }
  }
)

When requesting an interface in a page:

// User login submission
    login() {
      // debugger
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return
        if (valid) {const userInfo = {
            username: this.loginForm.username,
            password: this.loginForm.password
          }
          // Remove token before login
          window.sessionStorage.removeItem('DT')
          const { data: res } = await this.$http.post('/system/login', userInfo)
          if (res.code !== 200) {
            this.initCaptcha()
            return
          }
          this.$message.success('Login succeeded')
          window.sessionStorage.setItem('DT', res.result.token)
          this.$router.push('/main')
        }
      })
    }
 

summary

  • Request Interceptor: in fact, it is to execute the data to be added first, and then execute Ajax. If the process of adding data is extracted, it becomes the so-called request interceptor
  • Response Interceptor: after the request result is returned, it does not export directly, but first processes the response code and so on, and then exports it to the page. If the processing process of the object response code is extracted, it becomes the so-called response interceptor

Posted by nick1 on Sat, 11 Sep 2021 18:22:28 -0700