【axios】axios学习


1,axios.defaults.baseURL = 'https://api.example.com' // 配置请求的基础路径

2,axios.defaults.headers.comon['Authorization'] = TOKEN // 全局设置请求token

3,axios.defaults.timeout = 3000 // 设置超时时间

4,axios.interceptors.request.use(function(config){ // 拦截器,在发起请求的时候触发

    // 在这里写发起请求需要做的操作

  return config // 固定写法,回调函数必须返回config

  })

  axios.interceptors.response.use(function(config) {

    // 在服务器响应是触发

  return config // 必须返回config

  })

5,axios的then方法和catch方法,请求成功调用then,请求失败调用catch

        axios.get('http://127.0.0.1:3000/')
        .then(res => {
            console.log(res)
        })

 最终会返回一个axios封装好的对象,其中data是服务器返回的数据,其余的是本次请求的参数。

6,axios请求传参的方式。

(1)在url中直接传参, 'https://api.example.com/user?username='admin''

  后端用req.query.username获得admin

(2)后端请求地址为'https://api.example.com/user/:username'

  axios发起请求的地址'https://api.example.com/user/admin'

  后端通过req.params.username获得admin

(3)通过对象传参 

axios.get('http://127.0.0.1:3000/', { params: {
            userid: '1'
        }})
        .then(res => {
            console.log(res)
        })
axios.post('http://127.0.0.1:3000/post', {
            userid: '1'
        })
        .then(res => {
            console.log(res)
        })

值得一提的是,get方法通过这种方式传参时,需要将json对象传给params再传给axios,而其他的put post等方法则不需要,直接传json对象就可以了。

后端通过req.query.userid获得传过来的id

除了上述传参方式,axios还支持URLSearchParams 传参,详情可以参考axios官网

注:仅自己的理解,酌情参考,详情看官方api

axios:https://github.com/axios/axios