Home > Web Front-end > JS Tutorial > body text

Introduction to the method of using axios request interception in Vue

不言
Release: 2018-10-24 16:38:11
forward
2218 people have browsed it

This article brings you an introduction to the method of using axios request interception in Vue. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Preface

I won’t explain too much about the basic use of axios. How to use it can be seen in the axios document instructions·Axios Chinese instructions

Here and Let's share the use of axios interception in actual projects

Many people have seen the interceptor column in the official documentation of axios. Some people may be a little confused, because the document only tells you that there is this thing. It doesn't tell you under what circumstances it is used. Many beginners will give up using the axios interceptor. After all, the interceptor can be dispensed with, but using the interceptor will reduce a lot of unnecessary code in the page.

2. The UI framework used in the previous

project is iview

The following friendly tips all use the message prompt component of iview ui, such as this.$Message.xxx
/api/request is just an example interface, actual development uses the interface provided by the backend.
code is the background status code. I am just giving an example here. Don’t ask me why my return code is different from yours... These all need to be communicated and agreed with the background.
The request header used is: axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'; As for why this request header is used, you can read my other article about axios sending two requests. There is an OPTIONS request problem
Because this request is used Therefore, you need to use the qs module, otherwise the backend will not recognize this data.

3. Not using request interception

If you don’t use request interception, it is also possible, but it will add a lot of code. Let’s take the login page as an example.

Introduction to the method of using axios request interception in Vue

##A simple page without any bells and whistles,|ω・)

//双向数据绑定获取值
let httpRequest = {};
httpRequest.loginName = this.loginName
httpRequest.password= this.password

this.$axios.post("/api/request", this.$qs.stringify(httpRequest)).then(data => {
    //特殊错误处理,状态为10时为登录超时
    if(data.data.code === 10){
        this.$Message.error("登录已超时,请重新登录")
        this.$router.push("/login")
    //其余错误状态处理    
    }else if(data.data.code != 0){
        this.$Message.error(data.data.msg)
    //请求成功
    }else if(data.data.code === 0){
        //进行成功业务逻辑
    }
    //.......
});
Copy after login
If Without request interception, each request and each status must be specially processed. If there are dozens of special status requests and many requests for each page, the page will become very long, bloated, and difficult to maintain.

3. Use request interception

We can extract the same request return code and write it in the request interception

After we set up the interception, after we The component code can be simplified a lot, let's take the login interface as an example:

In main.js

//请求发送拦截,把数据发送给后台之前做些什么......
axios.interceptors.request.use((request) => {

  //这个例子中data是loginName和password
  let REQUEST_DATA = request.data
  //统一进行qs模块转换
  request.data = qs.stringify(REQUEST_DATA)
  //再发送给后台
  return request;

}, function (error) {
  // Do something with request error
  return Promise.reject(error);
});

//请求返回拦截,把数据返回到页面之前做些什么...
axios.interceptors.response.use((response) => {
  //特殊错误处理,状态为10时为登录超时
  if (response.data.code === 10) {
    iView.Message.error("登录已超时,请重新登录");
    router.push("/login")
  //其余错误状态处理    
  } else if (response.data.code != 0) {
    iView.Message.error(response.data.msg)
  //请求成功
  } else if(response.data.code === 0){
    //将我们请求到的信息返回页面中请求的逻辑
    return response;
  }
 //......

}, function (error) {
  return Promise.reject(error);
});
Copy after login
//双向数据绑定获取值
let httpRequest = {};
httpRequest.loginName = this.loginName
httpRequest.password= this.password

this.$axios.post("/api/request", httpRequest).then(data => {
    //这是要先判断data,如果请求的数据状态code不为0,会被拦截,则data为undefined
    if(data){
        //进行请求返回成功逻辑
    }
});
Copy after login
Copy after login
In this way, we add interception to axios requests, which can reduce a lot of code logic and page It is more readable and maintainable

4. Others

This is the most basic usage of axios interception, of course it is more than that, we You can also expand and do more things. As long as your business needs it, axios interception can always help you. You need to draw inferences from one example. Tools are dead and people are alive. I can give you another small example, such as Set request signature.

Request signature is a communication method agreed between the front-end and the back-end. Encrypting the data can ensure the security of the data to a certain extent

Let’s take this login page as an example

//双向数据绑定获取值
let httpRequest = {};
httpRequest.loginName = this.loginName
httpRequest.password= this.password

this.$axios.post("/api/request", httpRequest).then(data => {
    //这是要先判断data,如果请求的数据状态code不为0,会被拦截,则data为undefined
    if(data){
        //进行请求返回成功逻辑
    }
});
Copy after login
Copy after login
Before we send the httpRequest data information to the background, we sign and encrypt the data

In
main.js, we intercept the sent data

//请求发送拦截
axios.interceptors.request.use((request) => {

  //获取请求的数据,这里是loginName和password
  let REQUEST_DATA = request.data
  //获取请求的地址,这里是/api/request
  let REQUEST_URL = request.url
   
  //设置签名并进行qs转换,且赋值给request的data,签名函数另外封装
  request.data = qs.stringify(requestDataFn(REQUEST_DATA, REQUEST_URL))
  //发送请求给后台
  return request;

}, function (error) {
  // Do something with request error
  return Promise.reject(error);
});

//已封装好的签名函数
function requestDataFn(data, method) {

  let postData = {}

  //时间戳,时间戳函数不作展示,也是已封装好的
  postData.timestamp = getNowFormatDate();

  //请求用户的session以及secretKey信息,为空是未登录,登录后我把它存在localStorage中,这个存在哪里都可以,这里只作为例子。
  postData.session = localStorage.getItem('session') || '';
  postData.secretKey = localStorage.getItem('secretKey') || '';
  
  //请求的地址,这里是/api/request
  postData.method = method;
    
  //请求的数据这里是loginName和password,进行base64加密
  let base64Data = Base64.encode(JSON.stringify(data));
   
  //设置签名并进行md5加密
  let signature = md5.hex(postData.secretKey + base64Data + postData.method + postData.session + postData.timestamp + postData.secretKey);
   
  //把数据再次进行加密
  postData.data = encodeURI(base64Data);

  postData.signature = signature;
   
  return postData
}
Copy after login
In this way, we complete the data encryption and signature, and then send it to the background.

Note: This is only shown as an example. If a signature is needed, how to sign is the result of communication between the front desk and the backend!The use of axios request interception is far more than this. How to use it specifically depends on the actual work and actual projects.

The above is the detailed content of Introduction to the method of using axios request interception in Vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!