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

Vue axios封裝

1. 始vue化專案

vue

1、vue環境搭建

安裝Node

網站上下載 node.exe 檔案 安裝

官網:http://nodejs.cn/download/

安裝node以後 內部繼承了npm工具

#檢視安裝成功否
> node --version

> npm --version
安裝 vue相關模組
#安裝 vue  -g 全域性安裝

npm install -g vue

#安裝 vue-cli

npm install -g vue-cli

2、建立vue專案

> vue init webpack vuedemo

注意:目錄問題,專案會建立到你的命令列上目錄位置

? Project name vue-case01
? Project description A Vue.js project
? Author
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? No
? Set up unit tests No
? Setup e2e tests with Nightwatch? No
? Should we run `npm install` for you after the project has been created? (recommended) npm

?專案名稱vue-case01
?專案描述:Vue.js專案
?作者
?Vue構建獨立的
?安裝vue-router ?是的
?使用ESLint來lint你的程式碼?沒有
?設定單元測試號
?用夜視器設定e2e測試?沒有
?我們是否應該在專案建立後為您執行' npm安裝' ?(推薦)npm

3、安裝axios

#要先進入 專案目錄
#一定要 --save
> npm install --save axios

4.修改映象源

檢視映象源
npm config get registry

修改映象源
npm config set registry https://registry.npm.taobao.org

2.封裝axios

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

![image-20201029072159325](C:\Users\wyx\Desktop\小實訓\day03 Django基礎 ORM語句進階\圖片\image-20201029072159325.png)

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)