axios 使用詳情
axios 安裝注冊
axios 安裝
npm install axios
axios 注冊
main.js 入口文件
import axios from 'axios' // 導入axios
Vue.prototype.$axios = axios // 將axios掛載到Vue實例上
axios GET,POST 請求
GET 請求
this.$axios
.get('/user?ID=12345')
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
const params = { ID: 12345 }
this.$axios
.get('/user', params)
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
POST 請求
const data = {
firstName: 'Fred',
lastName: 'Flintstone',
}
this.$axios
.post('/user', data)
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
axios API GET,POST 請求
【注意】get 請求使用 params 傳參,post 請求使用 data 傳參
GET 請求
this.$axios({
method: 'get',
url: '/user/12345',
params: {
firstName: 'Fred',
lastName: 'Flintstone',
},
})
this.$axios({
method: 'get',
url: '/user/12345',
})
POST 請求
this.$axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone',
},
})
自定義 axios 實例,統一配置請求響應
自定義 axios 實例
const baseUrl:'http://localhost:8080'
const baseApi:'/lba/inner/manager'
const uploadUrl:'http://localhost:8080/lba/inner/manager/file/upload'
const downloadUrl:'http://localhost:8080/lba/inner/manager/file/downloadUrl'
// 創建axios實例
const instance=axios.create({
baseURL:${baseUrl}${baseApi},
withCredentials:false,
timeout:60000
})
創建請求時可用的配置:
{
url: '/user',// `url` 是用於請求的服務器 URL
method: 'get', // `method` 是創建請求時使用的方法// 默認是 get
// `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。
// 它可以通過設置一個 `baseURL` 便於為 axios 實例的方法傳遞相對 URL
baseURL: 'https://some-domain.com/api/',
// `transformRequest` 允許在向服務器發送前,修改請求數據
// 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法
// 后面數組中的函數必須返回一個字符串,或 ArrayBuffer,或 Stream
transformRequest: [function (data) {
// 對 data 進行任意轉換處理
return data;
}],
transformResponse: [function (data) {// `transformResponse` 在傳遞給 then/catch 前,允許修改響應數據
// 對 data 進行任意轉換處理
return data;
}],
headers: {'X-Requested-With': 'XMLHttpRequest'},// `headers` 是即將被發送的自定義請求頭
// `params` 是即將與請求一起發送的 URL 參數
// 必須是一個無格式對象(plain object)或 URLSearchParams 對象
params: {
ID: 12345
},
// `paramsSerializer` 是一個負責 `params` 序列化的函數
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// `data` 是作為請求主體被發送的數據
// 只適用於這些請求方法 'PUT', 'POST', 和 'PATCH'
// 在沒有設置 `transformRequest` 時,必須是以下類型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 瀏覽器專屬:FormData, File, Blob
// - Node 專屬: Stream
data: {
firstName: 'Fred'
},
// `timeout` 指定請求超時的毫秒數(0 表示無超時時間)
// 如果請求話費了超過 `timeout` 的時間,請求將被中斷
timeout: 1000,
// `withCredentials` 表示跨域請求時是否需要使用憑證
withCredentials: false, // 默認false
// `adapter` 允許自定義處理請求,以使測試更輕松
// 返回一個 promise 並應用一個有效的響應 (查閱 [response docs](#response-api)).
adapter: function (config) {
/* ... */
},
// `auth` 表示應該使用 HTTP 基礎驗證,並提供憑據
// 這將設置一個 `Authorization` 頭,覆寫掉現有的任意使用 `headers` 設置的自定義 `Authorization`頭
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType` 表示服務器響應的數據類型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // 默認的
// `xsrfCookieName` 是用作 xsrf token 的值的cookie的名稱
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` 是承載 xsrf token 的值的 HTTP 頭的名稱
xsrfHeaderName: 'X-XSRF-TOKEN', // 默認的
// `onUploadProgress` 允許為上傳處理進度事件
onUploadProgress: function (progressEvent) {
// 對原生進度事件的處理
},
// `onDownloadProgress` 允許為下載處理進度事件
onDownloadProgress: function (progressEvent) {
// 對原生進度事件的處理
},
// `maxContentLength` 定義允許的響應內容的最大尺寸
maxContentLength: 2000,
// `validateStatus` 定義對於給定的HTTP 響應狀態碼是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者設置為 `null` 或 `undefined`),promise 將被 resolve; 否則,promise 將被 rejecte
validateStatus: function (status) {
return status >= 200 && status < 300; // 默認的
},
// `maxRedirects` 定義在 node.js 中 follow 的最大重定向數目
// 如果設置為0,將不會 follow 任何重定向
maxRedirects: 5, // 默認的
// `httpAgent` 和 `httpsAgent` 分別在 node.js 中用於定義在執行 http 和 https 時使用的自定義代理。允許像這樣配置選項:
// `keepAlive` 默認沒有啟用
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy' 定義代理服務器的主機名稱和端口
// `auth` 表示 HTTP 基礎驗證應當用於連接代理,並提供憑據
// 這將會設置一個 `Proxy-Authorization` 頭,覆寫掉已有的通過使用 `header` 設置的自定義 `Proxy-Authorization` 頭。
proxy: {
host: '127.0.0.1',
port: 9000,
auth: : {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// `cancelToken` 指定用於取消請求的 cancel token
// (查看后面的 Cancellation 這節了解更多)
cancelToken: new CancelToken(function (cancel) {
})
}
axios 請求攔截
請求攔截器的主要功能:
- 添加公共請求頭
- 數據加密
- 設置 baseURL
- 設置跨域請求是否使用憑證
- 設置請求超時時間
// 添加請求攔截器
axios.interceptors.request.use(
function (config) {
// 在發送請求之前做些什么
return config
},
function (error) {
// 對請求錯誤做些什么
return Promise.reject(error)
},
)
axios 響應攔截
響應信息:
{
// `data` 由服務器提供的響應
data: {},
// `status` 來自服務器響應的 HTTP 狀態碼
status: 200,
// `statusText` 來自服務器響應的 HTTP 狀態信息
statusText: 'OK',
// `headers` 服務器響應的頭
headers: {},
// `config` 是為請求提供的配置信息
config: {}
}
響應攔截器主要功能:
- 對響應數據 進行格式轉化
- 對響應狀態碼進行統一處理
2.1 成功放行
2.2 失敗 提示失敗原因 - 對響應數據進行解密
// 添加響應攔截器
axios.interceptors.response.use(
function (response) {
// 對響應數據做點什么
return response
},
function (error) {
// 對響應錯誤做點什么
return Promise.reject(error)
},
)
axios 二次封裝 與 使用
axios 二次封裝
/api/http.js
import axios from 'axios'
// 創建 axios 實例
let baseUrl = '/'
if (process.env.NODE_ENV === 'production') {
baseUrl = 'localhost:5000'
} else if (process.env.NODE_ENV === 'development') {
baseUrl = 'localhost:5000'
}
const service = axios.create({
baseURL: baseUrl,
headers: {
get: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
},
post: {
'Content-Type': 'application/json;charset=utf-8',
},
},
// 是否跨站點訪問控制請求
withCredentials: false,
timeout: 30000,
//請求數據轉換
transformRequest: [
(data) => {
return JSON.stringify(data)
},
],
//相應數據轉換
transformResponse: [
(data) => {
if (typeof data === 'string' && data.startsWith('{')) {
data = JSON.parse(data)
}
return data
},
],
})
// 請求攔截器
service.interceptors.request.use(
(config) => {
// 讓每個請求攜帶自定義 token
config.headers['Authorization'] = 'token'
return config
},
(error) => {
// 錯誤拋到業務代碼
error.data = {}
error.data.msg = '服務器異常,請聯系管理員!'
return Promise.resolve(error)
},
)
// 響應攔截器
service.interceptors.response.use(
(response) => {
const status = response.status
let msg = ''
if (status < 200 || status >= 300) {
// 處理http錯誤,拋到業務代碼
msg = showStatus(status)
if (typeof response.data === 'string') {
response.data = { msg }
} else {
response.data.msg = msg
}
//攔截異常(通知)
Notification({
title: '提示',
message: msg,
type: 'error',
})
}
return response
},
(error) => {
// 錯誤拋到業務代碼
error.data = {}
error.data.msg = '請求超時或服務器異常,請檢查網絡或聯系管理員!'
return Promise.resolve(error)
},
)
const showStatus = (status) => {
let message = ''
switch (status) {
case 400:
message = '請求錯誤(400)'
break
case 401:
message = '未授權,請重新登錄(401)'
break
case 403:
message = '拒絕訪問(403)'
break
case 404:
message = '請求出錯(404)'
break
case 408:
message = '請求超時(408)'
break
case 500:
message = '服務器錯誤(500)'
break
case 501:
message = '服務未實現(501)'
break
case 502:
message = '網絡錯誤(502)'
break
case 503:
message = '服務不可用(503)'
break
case 504:
message = '網絡超時(504)'
break
case 505:
message = 'HTTP版本不受支持(505)'
break
default:
message = `連接出錯(${status})!`
}
return `${message},請檢查網絡或聯系管理員!`
}
export { service as axios }
統一管理接口
/api/login.js
// 登錄接口
import { axios } from './axios'
const userApi = {
login: '/api/login',
logout: '/api/logout',
}
export function login(parameter) {
return axios({
url: userApi.test,
method: 'get',
params: parameter,
})
}
export function logout(parameter) {
return axios({
url: userApi.test,
method: 'get',
params: parameter,
})
}
頁面中使用接口
login.vue
import {login} form '@/api/login'
login(data).then((res)=>{consloe.log(res)})