axios

一、基本使用

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)
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值