一、基本使用
1. 发送request 请求
axios.request({
url: "http://123.207.32.32:8080/home/multidata",
method: "get"
}).then( res => {
console.log("res", res)
})
2. 发送get 请求
// http://123.207.32.32:9001/lyric?id=500665346
axios.get("http://123.207.32.32:9001/lyric",{
params: {
id: 500665346
}
}).then( res => {
console.log("res", res.data)
})
3. 发送post 请求
axios.post("http://152.136.185.210:5000/login", {
name: "coderwhy",
password: 123456
}).then(res => {
console.log("res", res.data)
})
axios.post("http://152.136.185.210:5000/login", {
data: {
name: "coderwhy",
password: 123456
}
}).then(res => {
console.log("res", res.data)
})
二、公共的基 础配置
const baseURL = "http://123.207.32.32:8000";
axios.defaults.baseURL = baseURL;
axios.defaults.timeout = 10000;
axios.defaults.headers = {'x-Requested-With':'XMLHttpRequest'}
axios.defaults.headers["token"] = "coderwhy"
axios.get("/home/multidata").then(res => {
console.log("res", res.data);
})
三、axios.all([ ]) 一次发送多个请求,当多个请求都有结果时,执行对应的then
axios.all([
axios.get("/home/multidata"),
axios.get("http://123.207.32.32:9001/lyric?id=500665346")
]).then(res => {
console.log("res", res)
})
四、创建axios 实例
// 配置只针对当前创建的实例 instance1
const instance1 = axios.create({
baseURL: "http://123.207.32.32:9001",
timeout: 10000,
headers: {}
})
instance1.get("/lyric", {
params: {
id: 500665346
}
}).then(res => {
console.log("res", res.data)
})
const instance2 = axios.create({
baseURL: "http://123.207.32.32:8000",
timeout: 6000,
headers: {}
})
五、拦截器
axios.interceptors.request.use((config) => {
if(config.url === '/user/info") {
config.headers["token"] = "coderwhy"
}, () => {}
})
六、封装类
// service/index.js
import axios from 'axios'
class HYRequest {
constructor(baseURL, timeout = 1000) {
this.instance = axios.create({
baseURL,
timeout
})
}
request(config) {
return new Promise((resolve, reject) => {
this.instance.request(config).then(res => {
resolve(res.data)
}).catch(err => {
reject(err)
})
})
}
get(config) {
return this.request({...config, methods: "get"})
}
post(config) {
return this.request({...config, methods: "post"})
}
}
export default new HTRequest("http://123.207.32.32:9001")
// main.js
hyRequest.request({
url: "/lyric?id=50665346"
}).then(res => {
console.log(res)
})
hyRequest.get({
url:"/lyric",
params: {
id: 500665346
}
}).then(res => {
console.log(res)
})