导入axios
cnpm npm install axios --save
import axios form 'axios'
axios({
url: 'http://123.207.32.32:8000/home/multidata',
method: 'get' //默认是get方式
// axios自动调用promise,并进入resolve函数继续调用
}).then(res=>{
console.log(res)
})
-------------------------------------------------------------------------------
axios({
url: 'http://123.207.32.32:8000/home/data?type=sell&page=3'
}).then(res=>{
console.log(res);
})
get请求参数拼接,可以这样写
http://123.207.32.32:8000/home/data?type=pop&page=1
axios({
url: 'http://123.207.32.32:8000/home/data',
params: {
type: 'pop',
page: 1
}
}).then(res=>{
console.log(res);
})
axios.all([
axios({
url: 'http://123.207.32.32:8000/home/multidata?',
params: {
callback: 'json123'
}
}),
axios({
url: 'http://123.207.32.32:8000/home/data'
})
]).then(res=>{
console.log(res[0]);
console.log(res[1]);
})
也可以分开来
axios.all([
axios({
url: 'http://123.207.32.32:8000/home/multidata?',
params: {
callback: 'json123'
}
}),
axios({
url: 'http://123.207.32.32:8000/home/data'
})
]).then(axios.spread((res1,res2)=>{
console.log(res1);
console.log(res2);
}))
axios.defaults.baseURL = 'http://123.207.32.32:8000'
axios.defaults.timeout = 5000
//创建对应的Axios实例, 不适用全局的Axios
const axios01 = axios.create({
baseURL: 'http://123.207.32.32:8000',
timeout: 5000,
})
axios01({
url: '/home/multidata',
params:{ }
}).then(res=>{
console.log(res);
})
请求另外一个服务器
const axios02 = axios.create({
baseURL: 'http://116.62.156.97:9003',
timeout: 5000
})
axios02({
url: '/index',
methods: 'get'
}).then(res=>{
console.log(res);
})
import axios from 'axios'
//config参数是一个对象,有url,params属性
//success参数是一个函数
export function request(config){
//1.创建axios实例
const instance = axios.create({
baseURL: 'http://123.207.32.32:8000',
timeout: 5000
})
//发生真正的网络请求
instance(config.baseConfig).then(res=>{
config.success(res)
}).catch(err=>{
config.failure(res)
})
}
import {request} from "./network/request";
request({
baseConfig: {
url: '/home/multidata'
},
success(res){
console.log(res);
},
failure(err){
console.log(err);
}
})
还可以更优雅,Promise嵌套
使用Promise包裹代码,调用promise的resolve方法和reject方法,调动者就不必传入success函数和failure函数了
export function request(config) {
return new Promise((resolve,reject)=>{
const instance = axios.create({
baseURL: 'http://123.207.32.32:8000',
timeout: 5000
})
instance(config).then(res=>{
resolve(res)
}).catch(err=>{
reject(res)
})
})
}
import {request} from "./network/request";
request({
url: '/home/multidata'
}).then(res=>{
//success
console.log(res);
}).catch(err=>{
console.log(err);
})
终极方案
instance本身就是Promise,再嵌套一次,没有必要啊!
export function request(config) {
const instance = axios.create({
baseURL: 'http://123.207.32.32:8000',
timeout: 5000
})
return instance(config)
}
import {request} from "./network/request";
request({
url: '/home/multidata'
}).then(res=>{
//success
console.log('kcl');
console.log(res);
}).catch(err=>{
console.log(err);
})