本文檔主要是講解一些
axios的基礎配置,實際umi項目中一般會采用dva/fetch去請求數(shù)據(jù)。如果是想建立簡單的數(shù)據(jù)請求可以采用這篇文檔去配置;實際的項目中如果,如果項目的業(yè)務較復雜,想在umi項目中引入axios發(fā)起數(shù)據(jù)請求??梢詤⒖己罄m(xù)文檔(二)持續(xù)更新中......
引入 安裝 axios
yarn add axios
編寫axios文件
在項目src文件下,新建文件夾apiConfig,新增文件request.js, 編寫axios請求數(shù)據(jù)時,需要對URL、及返回結果的處理:
import axios from 'axios'
// 基本配置
axios.defaults.baseURL = "http://localhost:8001/ucc/" //api前綴
const axios= axios.create({
xsrfCookieName: 'xsrf-token' , // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名稱
timeout: 1000, // 如果請求話費了超過 `timeout` 的時間,請求將被中斷
proxy: { // 'proxy' 定義代理服務器的主機名稱和端口
host: '10.10.10.198',
port: 9000,
},
});
instance.interceptors.request.use(function (config) {
return config;
}, function (error) {
return Promise.reject(error);
});
instance.interceptors.response.use(function (response) {
return response // 下節(jié)詳述
}, function (error) {
return Promise.reject(error);
});
export default axios;
相應結構
某個請求的響應包含以下信息:
{
// `data` 由服務器提供的響應
data: {},
// `status` 來自服務器響應的 HTTP 狀態(tài)碼
status: 200,
// `statusText` 來自服務器響應的 HTTP 狀態(tài)信息
statusText: 'OK',
// `headers` 服務器響應的頭
headers: {},
// `config` 是為請求提供的配置信息
config: {},
// 'request'
// `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance the browser
request: {}
}
在項目中使用 index.js
import axiosfrom '@/utils/request';
import { stringify } from 'qs'; // 一個查詢字符串解析和字符串化庫,增加了一些安全性。
componentDidMount() {
let params={
pageSize:10,
pageIndex:1,
}
// 執(zhí)行get請求:
axios.get(`ucc/modules/basic/part_info/partInfoList?${stringify(params)}`)
.then((res) => {
console.log('res', res)
});
// 執(zhí)行post請求:
axios.get(`ucc/modules/basic/part_info/partInfoList`, {
pageSize:10,
pageIndex:1,
})
.then((res) => {
console.log('res', res)
})
}