介紹
Axios 是一個基于promise網絡請求庫,作用于node.js和瀏覽器中
特性
- 從瀏覽器創建 XMLHttpRequests
- 從 node.js 創建 http 請求
- 支持 Promise API
- 攔截請求和響應
- 轉換請求和響應數據
- 取消請求
- 自動轉換JSON數據
- 客戶端支持防御XSRF
安裝
項目中
npm install axios
yarn add axios
學習階段
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.3.6/axios.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.3.6/axios.min.js"></script>
基本使用
axios({//方法method: "",//urlurl: "",//設置請求體//data: {}
}).then(response => {console.log(response);//...
});
API
axios.request(config)
axios.request({//方法method: "",//urlurl: "",
}).then(response => {console.log(response);//...
});
axios.post(url[, data[, config]])
axios.post("http://....", {"body":"喜大普奔","postId":2
}).then(response => {console.log(response);//...
});
其他
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
axios返回結果
config:為axios配置項,
data:服務器返回的數據,axios默認做json轉換。
headers:http響應頭
request: 原生ajax對象
status:狀態碼
statusText:狀態描述
axios 配置對象
這些是用于發出請求的可用配置選項。
{url: '/user',method: 'get', // defaultbaseURL: 'https://some-domain.com/api/',//對請求數據做預先處理transformRequest: [function (data, headers) {// Do whatever you want to transform the datareturn data;}],//對響應數據進行預處理transformResponse: [function (data) {// Do whatever you want to transform the datareturn data;}],// 請求頭信息配置headers: {'X-Requested-With': 'XMLHttpRequest'},//發送請求時url后邊的參數?id=12345&name=張三params: {ID: 12345,name:"張三"},// `paramsSerializer` is an optional config in charge of serializing `params` 一般用的不多paramsSerializer: {encode?: (param: string): string => { /* Do custom ops here and return transformed string */ }, // custom encoder function; sends Key/Values in an iterative fashionserialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ), // mimic pre 1.x behavior and send entire params object to a custom serializer func. Allows consumer to control how params are serialized.indexes: false // array indexes format (null - no brackets, false (default) - empty brackets, true - brackets with indexes)},//第一種data形式,對象形式data: {firstName: 'Fred'},//第一種data形式,字符串形式data:'Country=Brasil&City=Belo Horizonte',//請求時間timeout: 1000,//跨域請求是否把cookie攜帶過去,false不攜帶withCredentials: false,responseType: 'json', // defaultresponseEncoding: 'utf8', // default// `xsrfCookieName` is the name of the cookie to use as a value for xsrf tokenxsrfCookieName: 'XSRF-TOKEN', // default// `xsrfHeaderName` is the name of the http header that carries the xsrf token valuexsrfHeaderName: 'X-XSRF-TOKEN', // default...//代理,一般用在nodejs里面proxy: {protocol: 'https',host: '127.0.0.1',// hostname: '127.0.0.1' // Takes precedence over 'host' if both are definedport: 9000,auth: {username: 'mikeymike',password: 'rapunz3l'}},...
}
設置默認配置
axios.defaults.method = "get";
axios.defaults.baseURL = "https://api.apiopen.top";
axios.defaults.params = {page: 0,size: 5
}
axios.defaults.timeout = 3000
axios({//urlurl: "/api/getHaoKanVideo"
}).then(response => {console.log(response);
});
創建實例對象發送請求
const a1 = axios.create({baseURL: 'https://some-domain.com/api/',timeout: 1000,headers: {'X-Custom-Header': 'foobar'}
});
const a2 = axios.create({baseURL: 'https://api.apiopen.top',timeout: 1000,headers: {'X-Custom-Header': 'foobar'}
});
//發送請求
a1({url:"xxxx",method:"get"
}).then(response => {console.log(response);
})
當需要請求不同域名發送不同請求時可以創建實例對象去發送請求。
下面列出了可用的實例方法。指定的配置將與實例配置合并。
axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#options(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
axios#getUri([config])
攔截器
攔截器其實是一些函數,可以在請求和響應之前處理數據、權限判斷等。
//請求攔截器
axios.interceptors.request.use(function (config) {//可以對config進行設置throw ("error")//return config;
}, function (error) {return Promise.reject(error);
});//響應攔截器
axios.interceptors.response.use(function (response) {//可以對response進行處理return response;
}, function (error) {return Promise.reject(error);
});axios({method:"get",url: "http://localhost:3300/api/getHaoKanVideo"
}).then(response => {console.log(response);
});
如果請求攔截器拋出異常,那么響應攔截器執行use中第二個參數回調方法。
請求攔截器執行順序與響應攔截器不同:
axios.interceptors.request.use(function (config) {console.log("請求攔截器-1")return config;
}, function (error) {return Promise.reject(error);
});
axios.interceptors.request.use(function (config) {console.log("請求攔截器-2")return config;
}, function (error) {return Promise.reject(error);
});//響應攔截器
axios.interceptors.response.use(function (response) {console.log("請求攔截器-1")return response;
}, function (error) {return Promise.reject(error);
});
axios.interceptors.response.use(function (response) {console.log("請求攔截器-2")
}, function (error) {return Promise.reject(error);
});axios.defaults.method = "get";
axios.defaults.baseURL = "https://api.apiopen.top";
axios.defaults.params = {page: 0,size: 5
}
axios({//urlurl: "/api/getHaoKanVideo"
}).then(response => {console.log("執行結果-3")console.log(response);
});
執行的結果為:
請求攔截器后加入的會先執行。