axios的基本使用
1.第一步先安装axios
npm Install --save axios
2.第二步在需要用axios的地方导入
import axios from “axios ”
3.简单的请求数据
axios({
url: 'http://152.136.185.210:8000/home/multidata',
// method: 'post'
}).then(res => {
console.log(res);
})
axios({
url: 'http://152.136.185.210:8000/home/data',
//专门针对get请求的参数拼接
params: {
type: 'pop',
page: 1
}
}).then(res => {
console.log(res);
})
多个同步请求
//2.axios发送并发请求
//并发请求到达后进行下一步
// axios.all([axios({
// url: 'http://152.136.185.210:8000/home/multidata',
// }),axios({
// url: 'http://152.136.185.210:8000/home/data',
// //专门针对get请求的参数拼接
// params: {
// type: 'sell',
// page: 5
// }
// })])
// .then(res => {
// console.log(res);
// }
// )
axios全局配置和拦截器
import axios from 'axios'
export function request(config) {
// 1.创建axios的实例
const instance = axios.create({
baseURL: 'http://123.207.32.32:8000',
timeout: 5000
})
// 2.axios的拦截器
// 2.1.请求拦截的作用
instance.interceptors.request.use(config => {
// console.log(config);
// 1.比如config中的一些信息不符合服务器的要求
// 2.比如每次发送网络请求时, 都希望在界面中显示一个请求的图标
// 3.某些网络请求(比如登录(token)), 必须携带一些特殊的信息
return config
}, err => {
// console.log(err);
})
// 2.2.响应拦截
instance.interceptors.response.use(res => {
// console.log(res);
return res.data
}, err => {
console.log(err);
})
// 3.发送真正的网络请求
return instance(config)
}
// export function request(config) {
// return new Promise((resolve, reject) => {
// // 1.创建axios的实例
// const instance = axios.create({
// baseURL: 'http://123.207.32.32:8000',
// timeout: 5000
// })
//
// // 发送真正的网络请求
// instance(config)
// .then(res => {
// resolve(res)
// })
// .catch(err => {
// reject(err)
// })
// })
// }
// export function request(config) {
// // 1.创建axios的实例
// const instance = axios.create({
// baseURL: 'http://123.207.32.32:8000',
// timeout: 5000
// })
//
// // 发送真正的网络请求
// instance(config.baseConfig)
// .then(res => {
// // console.log(res);
// config.success(res);
// })
// .catch(err => {
// // console.log(err);
// config.failure(err)
// })
// }
// export function request(config, success, failure) {
// // 1.创建axios的实例
// const instance = axios.create({
// baseURL: 'http://123.207.32.32:8000',
// timeout: 5000
// })
//
// // 发送真正的网络请求
// instance(config)
// .then(res => {
// // console.log(res);
// success(res);
// })
// .catch(err => {
// // console.log(err);
// failure(err)
// })
// }
// function test(aaa, bbb) {
// // aaa('Hello World')
// bbb('err message')
// }
//
// test(function (res) {
// console.log(res);
// }, function (err) {
// console.log(err);
// })