axios的基本介绍
一、axios的介绍:
官方网站:http://www.axios-js.com
概念:aixos是一个基于Promise(ES6语法中用于处理异步的)的HTTP库,用于浏览器和node.js中。
作用:
浏览器中创建XMLHttpRequests
从node.js中创建http请求
支持Promise API
拦截请求和响应
转换请求数据和响应数据
取消请求
自动转换JSON数据
客户端支持防御XSRF
安装命令:npm install axios
使用:import axios from ‘axios’
二、发送基本请求
get请求:
axios对象调用get方法,.then()成功回调,.catch()失败回调。
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
post请求:
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
通用的请求:
axios({
methods: 'post',
url: 'http://127.0.0.1:8000/users/',
data: {
name: 'qiurx'
})
.then(res=>{
console.log(res.data);
})
.catch(function (error) {
console.log(error);
})
三、axios创建实例
let instance = axios.create({
url:'http://127.0.0.1:8000/users/',
imeout:3000,
method:'post'
});
//即可调用方法,和axios实例同
instance.get('http://jsonplaceholder.typicode.com/users').then(Response=>{
console.log(Response);
});
四,axios的请求拦截器和响应拦截器的使用
可以先拦截请求或响应,然后再由then 或处理catch。
// Add a request interceptpr
axios.interceptors.request.use(function(config){
// Do something before request is sent
return config;
}
)