axios Profile
axios HTTP client is a browser-based Promise and nodejs, which itself has the following characteristics:
- Create XMLHttpRequest from the browser
- Http requests sent from node.js
- Support Promise API
- Intercept request and response
- Conversion request and response data
- Cancellation request
- Automatically convert JSON data
- Client support to prevent CSRF / XSRF
installation
npm install
$ npm install axios --save
Introduced by cdn
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Send GET request
// created:vue生命周期中的钩子函数,在这个时间点,data中的数据已经注入到响应式系统中
created(){ axios.get('api/getData.php',{ // 还可以直接把参数拼接在url后边 params:{ title:'眼镜' } }).then(function(res){ this.goodsList = res.data; }).catch(function (error) { console.log(error); }); }
response.data is the return of the real background data
POST request sent
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }).then(function (response) { console.log(response); }).catch(function (error) { console.log(error); }); // 注意: 如果发送请求时,发现传递的参数是对象,那么可用如下方式传参数 // var params = new URLSearchParams(); // params.append('title', '眼镜'); // params.append('id',1); // axios.post('/user', params) // .then(function(res){}) // .catch(function(error){});
response.data is the return of the real background data
Executing a plurality of concurrent requests
//获得用户信息的请求
function getUserAccount() { return axios.get('/user/12345'); } //获取用户许可证的请求 function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all( [ getUserAccount(), getUserPermissions() ] ) .then(axios.spread(function (acct, perms) { //两个请求现已完成 }) );
And in response to the request interceptor interceptors
//请求拦截器
axios.interceptors.request.use( function (config) { // 在发送请求之前做些什么 return config; }, function (error) { // 对请求错误做些什么 return Promise.reject(error); } ); //响应拦截器 axios.interceptors.response.use( function (config) { // 对响应数据做点什么 return config; }, function (error) { // 对响应错误做点什么 return Promise.reject(error); } );
Vue axios when sending the POST request, the process parameters
1. Download third-party modules qs -> npm install qs --save-dev
2. treatment
// 第一种: 直接在发送的时候,对数据进行qs.stringify处理
// 缺点: 如果项目大,有大量的请求需要发送,那么一个一个加会很麻烦
axios.post("/checkLogin.php", qs.stringify({ name, pwd })); // 第二种: 使用axios.create创建一个新的axios实例,统一对数据进行处理, 同时也要借助qs模块 const Axios = axios.create({ baseURL: '/api', transformRequest: [function (data) { const d = qs.stringify(data) return d; }] }) Axios.post("/checkLogin.php", { name, pwd });