1. 程式人生 > 實用技巧 >axios封裝

axios封裝

1. 始vue化專案

https://www.cnblogs.com/xiaonq/p/11027880.html

vue init webpack deaxios # 使用腳手架建立專案 deaxios(專案名,隨便取得)
cd deaxios # 進入專案
npm install axios -S # 安裝axios

 

2.封裝axios

2.1 src資料夾下新建http資料夾, 用來放網路請求相關的檔案

2.2 src/http 資料夾下, 建立 index.js 檔案, 對axios進行封裝

/* eslint-disable */
//第一步:例項化axios物件,並設定 1.請求地址;2.超時時間;3.設定請求頭資料格式
const axios = require('axios'); // 建立axios物件
// import qs from 'qs'
axios.defaults.baseURL = 'http://192.168.56.100:8888'; // vue請求後端地址
axios.defaults.timeout = 10000; // 多久超時
axios.defaults.withCredentials = true; // 跨域訪問需要傳送cookie
時一定要加axios.defaults.withCredentials = true;
/**
* 設定請求傳遞資料的格式(看伺服器要求的格式)
* x-www-form-urlencoded
* 預設提交表單
* 把資料物件序列化成 表單資料
*/
// axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
// axios.defaults.transformRequest = data => qs.stringify(data);
/**
* 設定預設提交 json
* 把資料物件序列化成 json 字串
*/
axios.defaults.headers['Content-Type'] = 'application/json'; // 設定預設提
交 json
axios.defaults.transformRequest = data => JSON.stringify(data); // 把資料物件
序列化成 json 字串
// 第二步:對請求攔截器,和響應攔截器進行封裝
/**
* 請求攔截器: 傳送請求前需要呼叫這個函式
1.當沒有登入時,直接跳轉到登入頁
2.請求傳送前把token獲取,設定到header中
*/
axios.interceptors.request.use(config => {
// 從localStorage中獲取token
let token = localStorage.getItem('token');
// 如果有token, 就把token設定到請求頭中Authorization欄位中
token && (config.headers.Authorization = token);
return config;
}, error => {
return Promise.reject(error);
});
/**
* 響應攔截器:當後端返回資料給vue時會呼叫這個函式
1.沒次返回403錯誤時,跳轉到login
*/
axios.interceptors.response.use(response => {
// 當響應碼是 2xx 的情況, 進入這裡
debugger
return response.data;
}, error => {
// 當響應碼不是 2xx 的情況, 進入這裡
debugger
return error
});
//第三步:使用上面的axios物件,對get請求和post請求進行封裝
/**
* get方法,對應get請求
* @param {String} url [請求的url地址]
* @param {Object} params [請求時攜帶的引數]
*/
export function get(url, params, headers) {
return new Promise((resolve, reject) => {
axios.get(url, { params, headers }).then(res => {
resolve(res.data.ResultObj)
}).catch(err => {
reject(err.data)
})
})
}
/**
* post方法,對應post請求
* @param {String} url [請求的url地址]
* @param {Object} params [請求時攜帶的引數]
**/
export function post(url, params, headers) {
return new Promise((resolve, reject) => {
axios.post(url, params, headers).then((res) => {
resolve(res.data)
}).catch((err) => {
debugger
reject(err.data)
})
})
}
export default axios; //一定要匯出函式

2.3 src/http 目錄下建立 apis.js檔案, 用來寫 介面地址列表

/* eslint-disable */
// 介面資訊, 生成請求方法
// 引入 get方法, post方法
import { get, post } from './index'
// 使用者登入
export const login = (params, headers) => post("/user/login/", params, headers)