1、为什么vue项目中要使用axios来发送ajax请求?
vue本身它是不支持直接发送ajax请求的,需要用到axios。
2、axios?
axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:
- 从浏览器中创建 XMLHttpRequest
- 从 node.js 发出 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据
- 客户端支持防止 CSRF/XSRF
3、vue项目引入axios
(1)安装依赖
npm install axios -S
(2)在src/main.js中引入
import axios from 'axios'
Vue.prototype.$http = axios
//添加了这两行代码之后,就能直接在组件的methods中使用 $http命令
使用的时候有如下几种写法
执行get请求:
$http.get('/login?username=admin&password=666666')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 也可以通过 params 对象传递参数
$http.get('/user', {
params: {
username:'admin',
password:666666
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
执行post请求
$http.post('/login', {
username:'admin',
password:666666
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
执行多个并发请求
function getUserAccount() {
return $http.get('/login/12345');
}
function getUserPermissions() {
return $http.get('/login/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then($http.spread(function (acct, perms) {
//两个请求现已完成
}));