1. 程式人生 > >vue中axios的統一封裝及調用

vue中axios的統一封裝及調用

return efault timeout 實例 remote class this func 0ms

一、axios.js

1、安裝axios

npm install axios --save

2、環境地址(config.js)

export default {
  // server: ‘http://localhost:8080‘ // 本地後臺接口地址
  // server: ‘http://10.2.22.88:8080‘ // 開發環境後臺接口地址
  server: ‘‘ // 正式環境後臺接口地址
}

2、引用

import axios from ‘axios‘
import {Message} from ‘element-ui‘
import config from ‘../config/config.js‘  //環境地址
import qs from 
‘qs‘

3、創建axios實例

const axios = axios.create({
  baseURL: config.server, // 本地環境地址
  timeout: 3000, // 請求超時時間,3000ms未響應則停止請求
  withCredentials: true, // 允許攜帶cookie
  responseType: ‘json‘,
  headers: {‘Content-Type‘: ‘application/json‘}
})

4、axios請求攔截器

axios.interceptors.request.use(function (config) {
  // 發送請求之前做一些處理
return config; }, function (error) { // 當請求異常時做一些處理 // 彈出錯誤消息 Message({ message: error.message, type: ‘error‘, duration: 5 * 1000 }) return Promise.reject(error); });

5、axios 響應攔截器

axios.interceptors.response.use(function (response) {
  // 返回響應時做一些處理
  //判斷返回狀態
  if (response.status === 200) {
       
//邏輯處理 } } else { // 非200狀態的處理 Message({ message: response.statusText, type: ‘error‘, duration: 5 * 1000 }) } return response; }, function (error) { // 當響應異常時做一些處理 Message({ message: error.message, type: ‘error‘, duration: 5 * 1000 }) return Promise.reject(error); });

二、api.js

調用

export const requestLogin = params =>
{
  return axios.post(`/remote/login`, params).then(res => res.data);
};

三、界面調用


            this.logining = true;
            var loginParams = { 
username: this.ruleForm2.account,
password: this.ruleForm2.checkPass
}; requestLogin(loginParams).then(data => { this.logining = false; if (code == 200) { this.$message({ message: ‘成功‘, type: ‘error‘ }); } else { this.$alert(res.message, "錯誤", { confirmButtonText: "確定" }); } });


vue中axios的統一封裝及調用