Vue でのネットワーク リクエスト (Axios) の単純なカプセル化 (リクエスト インターセプターとレスポンス インターセプターを含む)
アクシオスの紹介
Axios は、ブラウザーと Node.js で使用できる Promise ベースのネットワーク リクエスト ライブラリです。
特性
- ブラウザから XMLHttpRequest を作成する
- Node.jsからhttpリクエストを作成する
- サポート約束API
- リクエストとレスポンスをインターセプトする
- リクエストとレスポンスのデータを変換する
- リクエストのキャンセル
- タイムアウト処理
- クエリパラメータのシリアル化は、ネストされた項目の処理をサポートします
- リクエスト本文を次のように自動的にシリアル化します:
JSON (application/json)
Multipart / FormData (multipart/form-data)
URL エンコードされたフォーム (application/x-www-form-urlencoded) - リクエスト用にHTMLフォームをJSONに変換します
- JSONデータを自動変換する
- ブラウザとnode.jsのリクエストの進行状況を取得し、追加情報(速度、残り時間)を提供します。
- Node.jsの帯域幅制限を設定する
- 仕様に準拠した FormData および Blob (node.js を含む) との互換性
- クライアントは XSRF に対する防御をサポートします
インストール
npm install axios;
サンプルコード
https.js
import axios from "axios";
// const token = localStorage.getItem("accessToken");
export const https = axios.create({
baseURL: "http://localhost:3000",
timeout: 15000,
headers: {
},
});
// 添加请求拦截器
https.interceptors.request.use(
(config) => {
// 在发送请求之前做些什么
// if (token) {
// config.headers.accessToken = `Bearer ${token}`;
// }
return config;
},
(error) => {
// 对请求错误做些什么
// console.log(error);
return Promise.reject(error);
}
);
// 添加响应拦截器
https.interceptors.response.use(
(response) => {
// 2xx 范围内的状态码都会触发该函数。
// 对响应数据做点什么
// console.log(response);
if (response.status === 200) {
// console.log(Promise.resolve(response));
return Promise.resolve(response);
} else {
return Promise.reject(response);
}
// return response;
},
(error) => {
// 超出 2xx 范围的状态码都会触发该函数。
console.log(error);
// 对响应错误做点什么
return Promise.reject(error);
}
);
Vue で導入および使用される
import {
https } from "@/api/http";
//GET请求
// 写过的一个分页查询为例
https
.get("/display", {
params: {
pageSize: page.pageSize.value,
currentPage: page.currentPage.value,
},
})
.then((res) => {
console.log(res);
})
.catch((error) => {
console.log(error);
});
// 另一种写法
https.get("/display?ID=12345")
.then((res) => {
console.log(res);
})
.catch((error) => {
console.log(error);
});
//POST请求
https
.post("/display", {
id: id.value,
})
.then((res) => {
console.log(res);
})
.catch((error) => {
console.log(error);
});