web front-end entry to the actual: Vue project http request using the package Axios

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/wewfdf/article/details/102750494

When using axios intercept request response may be uniform, for example in response to a request response message intercepted us, the status code is determined so that the ejecting error message. Requesting disconnection request times out, you may then be conveniently used to process the request or catch.

installation

npm install axios --save

Establish http.js file

Establish a htttp.js in the / src / utils / directory

1. First and introducing axios router.

import axios from 'axios';
import router from '../router';

2. axios then set request parameters.

axios.defaults.timeout = 5000; //请求超时5秒
axios.defaults.baseURL ='';  //请求base url
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; //设置post请求是的header信息

If you use this code to the session features that make the request to carry cookie, you can add the following line:

axios.defaults.withCredentials = true

3. Then, we give the request to add interceptors, before the request is to be sent, we need to request to add information, such as the code below, we give the request to add header information, header added token, so every request carry the token information in the header. This is often used in our interface development.

//http request 拦截器
axios.interceptors.request.use(
  config => {
    let token = sessionStorage.getItem('token')
    if (token) {  // 判断是否存在token,如果存在的话,则每个http header都加上token
      config.headers = {
        'X-token': token
      }
    }

    return config
  }, 
  err => {
    return Promise.reject(err)
  }
)
web前端开发学习Q-q-u-n:784783012 ,分享学习的方法和需要注意的小细节,不停更新最新的教程和学习方法(详细的前端项目实战教学视频)

4. Next, we look at the return request interceptor.

For example, we send the request, it returns an error code if the back end, the front-end should prompt information. For example, the background does not have permission to return, does not allow access to jump to the login page, which can be done on the interceptor.

axios.interceptors.response.use(
  response => {
    if (response.data.code === 4003) {
      Toast({
        mes: '您没有权限操作!',
        timeout: 1500,
        callback: () => {
          router.go(-1);
        }
      });

      return false;
    }
    if (response.data.code === -1) {
      localStorage.removeItem('token')
      router.push({
        path:"/login",
        querry:{redirect: router.currentRoute.fullPath}//从哪个页面跳转
      })
    }
    return response
  }, 
  err => {
    if (err.code === 'ECONNABORTED' && err.message.indexOf('timeout') !== -1) {
      Toast({
          mes: '网络异常,连接超时...',
          timeout: 1500
      });
    }
    return Promise.reject(err)
  }
)

5. Now we get a method packaging:

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url, params={}, headers={}){
  return new Promise((resolve, reject) => {
    axios.get(url,{
      params: params,
      headers: headers
    })
    .then(response => {
      resolve(response.data);
    })
    .catch(err => {
      reject(err)
    })
  })
}

6. The method of resealing a post:

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

 export function post(url, data = {}){
   return new Promise((resolve, reject) => {
      axios.post(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
   })
 }
 web前端开发学习Q-q-u-n:784783012 ,分享学习的方法和需要注意的小细节,不停更新最新的教程和学习方法(详细的前端项目实战教学视频)

use

Introduced in main.js in:

import {post,get} from './utils/http'
//定义全局变量
Vue.prototype.$post = post;
Vue.prototype.$get = get;

Used in the assembly:

this.$post(url, params)
  .then((res) => {
    if (res.result === 'success') {
      this.$message({
        message: '登录成功!',
        type: 'success'
      })
      this.$router.push('/main')
    } else {
      this.$message.error(res.msg)
      this.refreshCode();
    }
  });

This code is transmitted post code sample user login request, another get request is the same approach.

Guess you like

Origin blog.csdn.net/wewfdf/article/details/102750494