1. 程式人生 > >Vue 封裝axios(四種請求)及相關介紹(十三)

Vue 封裝axios(四種請求)及相關介紹(十三)

# Vue 封裝axios(四種請求)及相關介紹 #### 首先axios是基於promise的http庫 promise是什麼? 1、主要用於非同步計算 2、可以將非同步操作佇列化,按照期望的順序執行,返回符合預期的結果 3、可以在物件之間傳遞和操作promise,幫助我們處理佇列 ## 一.首先安裝axios ```javascript npm install axios; // 安裝axios ``` ## 二.引入axios 我是根據網上學習的,在目錄下新建一個資料夾,新建兩個檔案 http.js 和 api.js **為什麼要新建這兩個檔案,** 我們在請求的時候 , 肯定要寫介面地址和引數吧,所以我們用http.js 寫四個請求方式 ,在api.js 裡面去呼叫,然後把所有的介面地址寫在api.js 裡面 ,這樣可以集中修改介面地址,方便管理。 **請求是請求** **地址是地址** ```javascript // 在http.js中引入axios import axios from 'axios'; // 引入axios import QS from 'qs'; // 引入qs模組,用來序列化post型別的資料,後面會提到 // Antdesign的全域性提示外掛 import { message } from "ant-design-vue"; ``` 配置 axios的操作 及 四種請求 ```javascript // 在http.js中引入axios import { message } from "ant-design-vue"; // 引入axios import axios from "axios"; import router from "@/router"; // 設定超時時間 axios.defaults.timeout = 10000; // 設定預設post的請求頭 axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8"; // 新增token 在登入成功後進行設定 export function setToken(token) { axios.defaults.headers.common["Authorization"] = "Bearer " + token; } /** * get方法,對應get請求 * @param {String} url [請求的url地址] * @param {Object} params [請求時攜帶的引數] */ export function get(url, params) { console.log(url, params); return new Promise((resolve, reject) => { axios .get(url, { params: params, }) .then(res => checkLogin(res)) .then(res => { resolve(res); }) .catch(err => { reject(err); }); }); } /** * post方法,對應post請求 * @param {String} url [請求的url地址] * @param {Object} params [請求時攜帶的引數] */ export function post(url, params, contentType) { // console.log(contentType ? contentType: 'application/json') console.log(url, params); return new Promise((resolve, reject) => { axios .post(url, params, { headers: { "Content-Type": contentType ? contentType : "application/json", }, }) .then(res => checkLogin(res)) .then(res => { if (res.data.code == 0) { resolve(res); } else { console.log(res); message.error(res.data.msg); } }) .catch(err => { reject(err); }); }); } /** * put方法,對應put請求 * @param {String} url [請求的url地址] * @param {Object} params [請求時攜帶的引數] */ export function put(url, params) { return new Promise((resolve, reject) => { axios .put(url, params) .then(res => checkLogin(res)) .then(res => { resolve(res); // Loading.service(true).close(); // Message({message: '請求成功', type: 'success'}); }) .catch(err => { reject(err); // Loading.service(true).close(); // Message({message: '載入失敗', type: 'error'}); message.error("載入失敗"); }); }); } /** * delete * @param {String} url [請求的url地址] * @param {Object} params [請求時攜帶的引數] */ export function deletedata(url, params) { return new Promise((resolve, reject) => { axios .delete(url, params) .then(res => checkLogin(res)) .then(res => { resolve(res); // Loading.service(true).close(); // Message({message: '請求成功', type: 'success'}); }) .catch(err => { reject(err); // Loading.service(true).close(); // Message({message: '載入失敗', type: 'error'}); message.error("載入失敗"); }); }); } function checkLogin(res) { // console.log(res) // res = JSON.parse(res) console.log(res.data); if (res.data.code === 401) { message.error(res.data.msg); router.push({ //核心語句 path: "/login", //跳轉的路徑 }); return false; } else if (res.data.code === 403) { message.error("許可權不足"); return false; } else if (res.data.code === 500) { message.error("伺服器內部錯誤"); return false; } else { return res; } } // function parseJSON(response) { // return response.json(); // } ``` 這個地方按理說是寫一個 攔截器 (axios是有直接攔截 請求之前 響應攔截) 但是沒有來急 就寫了 checkLogin 直接方法判斷 有時間我回來改 ### 注意 這個裡面的post請求 做了修改 就是請求的時候 響應頭可能不一樣 所以我們直接進行判斷 要是沒有使用預設,有的話用傳進來的 ## 三.介面管理 ```javascript /** * api介面統一管理 */ // eslint-disable-next-line no-unused-vars import QS from "qs"; //引入進來四種方式 import {get, post, deletedata, put} from "./http"; //這是和代理相對應的頭 var baseURL = "engine/"; //舉例子: //這是post的,需要進行序列化的 export const login = data => post(baseURL + "login/account", QS.stringify(data), "application/x-www-form-urlencoded"); //post直接用的 export const projectlist = data => get(baseURL + "projects/page", data); //等等 反正就是這個意思 名字自己起就行 data是來的引數 //QS.stringify(data) 序列化引數 放到url使用 //"application/x-www-form-urlencoded" 這是傳的響應頭的 上面的注意 裡面說了 post方法進行了處理 ``` ## 四.頁面進行請求 ```javascript //直接進行引入api.js裡面的方法 傳引數 接受回撥 //舉例子 import {login } from "../../../Api/api"; // 匯入我們的api介面 getPeople( { name:"小坦克", password:"3485" } ).then(res => { console.log(res) }); //其他的跟這個一個意思 ``` ## 五.設定代理 在 vue.config.js 檔案裡面 進行設定 注意proxy裡面的別寫錯了 和請求的對應起來 ```javascript devServer: { //proxy:{'/api':{}},代理器中設定/api,專案中請求路徑為/api的替換為target proxy: { '/engine': { // http://192.168.0.19:8082/engine target: 'http://192.168.0.19:8082/engine',//代理地址,這裡設定的地址會代替axios中設定的baseURL changeOrigin: true,// 如果介面跨域,需要進行這個引數配置 //ws: true, // proxy websockets //pathRewrite方法重寫url pathRewrite: { '^/engine': '/' //pathRewrite: {'^/api': '/'} 重寫之後url為 http://192.168.1.16:8085/xxxx //pathRewrite: {'^/api': '/api'} 重寫之後url為 http://192.168.1.16:8085/api/xxxx } } } } ``` 為什麼設定代理 就是讓所有的請求都走這個代理 ,你也可以設定多個代理保證名字別寫錯就行,也可以不設定代理,直接寫url請求也行 ,總之不是大問題 看看這個,講代理的意思的 [代理的那些事](https://www.jianshu.com/p/3de259ecc76e) ## 六.說一下請求頭 大體用三種: **application/x-www-form-urlencoded** **multipart/form-data** **application/json** http協議是建立在tcp/ip協議之上的應用層協議,主要包括三個部分,狀態行,頭部資訊,訊息主體。對應一個http請求就是:請求行,請求頭,請求體。 這個講的很細 有時間抄過來 [ https://blog.csdn.net/u014209205/article/details/81147783](https://blog.csdn.net/u014209205/article/details/81147783) 總結:具體使用就是三個部分 請求方法(http.js) 請求地址(api.js) 進行請求傳參得到回撥(頁面呼叫) 參考別人寫的好的 [vue中Axios的封裝和API介面的管理https://juejin.im/post/5b55c118f265da0f6f1aa354](https://juejin.im/post/5b55c118f265da0f6f1aa354) [Axios的封裝](https://www.cnblogs.com/chaoyuehedy/p/9931146.html) [幾種響應頭https://blog.csdn.net/u014209205/article/details/81147783](https://blog.csdn.net/u014209205/article/details/81147783) [代理的那些事https://www.jianshu.com/p/3de259ecc76e](https://www.jianshu.com/p/3de259ecc76e) [Vue中axios攔截器,傳token給後端https://www.jianshu.com/p/2035b1e923b2](https://www.jianshu.com/p/2035b1e923b2) [promise是什麼https://www.jianshu.com/p/1b63a13c2701](https://www.jianshu.com/p/1b63a1