Axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。
主要作用:
- 從瀏覽器中創建 XMLHttpRequests
- 從 node.js 創建 http 請求
- 支持 Promise API
- 攔截請求和響應
- 轉換請求數據和響應數據
- 取消請求
- 自動轉換 JSON 數據
- 客戶端支持防禦 XSRF
開發中常用來攔截請求和響應
axios github官網地址 (https://github.com/axios/axios)
各大瀏覽器對axios的支持情況:
axios如何使用?
方式一:使用npm安裝
$ npm install axios
方式二:瀏覽器安裝:
$ bower install axios
方式三:下載axios本地使用:
<script src="js/axios.js"></script>
首先在本地服務器新建test.php測試文件:
代碼如下:
<?php
header("Access-Control-Allow-Origin:*");
header('Access-Control-Allow-Headers:x-requested-with,content-type');
//$name = $_GET["userName"];
//$pwd = $_GET["userPwd"];
//$arr = array("code=>0","username"=>$name,"password"=>$pwd);
//echo json_encode($arr);
$rws_post = $GLOBALS['HTTP_RAW_POST_DATA'];
$mypost = json_decode($rws_post);
$name = (string)$mypost->userName;
$pwd = (string)$mypost->userPwd;
$arr = array("code=>0","username"=>$name,"password"=>$pwd);
echo json_encode($arr);
使用axios發送HTTP請求:
GET請求代碼如下:
axios.get('http://127.0.0.1/vue/test.php?userName=fengy&userPwd=123456')
.then(response =>{
console.log(response.data);
})
.catch(error =>{
console.log(error);
})
POST請求代碼如下:
axios.post('http://127.0.0.1/vue/test.php',{
userName:"Fengy",
userPwd:"123456"
})
.then(response =>{
console.log(response.data);
})
.catch(error =>{
console.log(error);
})*/
自定義實例方式代碼如下:
//1.自定義一個axios實例
var instance = axios.create({
//用於存儲一些公共信息
//注意點:配置baseURL時候最好以/結尾
baseURL: 'http://127.0.0.1/vue/test.php/',
timeout: 1000,
});
//2.利用自定義的axios實例發送請求
//注意點:發送請求的時候最好不要以/結尾
instance.post('test.php',{
userName:"Fengy",
userPwd:"123456"
})
.then(response =>{
console.log(response.data);
})
.catch(error =>{
console.log(error);
});
配置全局方式代碼如下:
//配置全局的baseURL
axios.defaults.baseURL = 'http://127.0.0.1/vue/test.php/';
axios.post('test.php',{
userName:"Fengy",
userPwd:"123456789"
})
.then(response =>{
console.log(response.data);
})
.catch(error =>{
console.log(error);
})
通過發送請求最終給我們返回的結果如下:
請求方法的別名
爲方便起見,爲所有支持的請求方法提供了別名
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
axios的基本使用與Ajax基本類似,Vue2.X項目基本使用axios框架請求數據