首页 > 技术文章 > axios传参/响应结果/全局配置/拦截器

xhxdd 2020-09-23 10:32 原文

axios传参

GET传参

通过URL传递参数

axios.get('/data?id=123')
     .then(ret=>{
      console.log(ret.data)
     })

restful形式的url传参

axios.get('/data/123')
     .then(ret=>{
      console.log(ret.data)
     })

params传参

axios.get('/data',{
    params:{
      id:123
      }
    })
    .then(ret=>{
      console.log(ret.data)
    })

 DELETE传参(与GET类似)

通过URL传递参数

axios.delete('/data?id=123')
     .then(ret=>{
      console.log(ret.data)
     })

restful形式的url传参

axios.delete('/data/123')
     .then(ret=>{
      console.log(ret.data)
     })

params传参

axios.delete('/data',{
    params:{
      id:123
      }
    })
    .then(ret=>{
      console.log(ret.data)
    })

 POST传参

通过选项传递参数(默认传递的是json格式的数据)

axios.post('/data',{
      uname: 'tom',
      pwd: '123'
     })
     .then(ret=>{
      console.log(ret.data)
     })

 通过URLSearchParams传递参数(application/x-www-form-urlencoded)

const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/data',params).then(ret=>{
      console.log(ret.data)
     })

PUT传参(与post类似)

通过选项传递参数(默认传递的是json格式的数据)

axios.put('/data',{
      uname: 'tom',
      pwd: '123'
     })
     .then(ret=>{
      console.log(ret.data)
     })

 

post与put都支持两种格式的参数传递,一种是json,一种是表单
用哪一种取决于后台(后端),json更方便一些

 

响应结果

data:实际响应回来的数据
headers:响应头信息
status:响应状态码(200正常的)
statusText:响应状态信息

axios.post('/data')
     .then(ret=>{
      console.log(ret)
     })

ret就是axios包装后的响应结果

 

 

全局配置

axios.defaults.timeout = 3000;   //超时时间

axios.defaults.baseUrl = "http://locahost:3000/app";   //默认地址

axios.defaults.headers['mytoken'] = "asdqwe123qw4e5qe6wqe3";   //设置请求头

 

常用设置默认地址与设置请求头

 

拦截器

请求拦截器(在请求发出之前设置一些信息)

请求拦截器设置请求头更加灵活
axios.interceptors.request.use(function(config){
    //在请求发出之前进行一些信息设置,将请求头中的 mytoken 设置为了 asdqwe123qw4e5qe6wqe3
    config.headers.mytoken = 'asdqwe123qw4e5qe6wqe3'
    return config;
},function(err){
    //处理响应的错误信息
})

 

 响应拦截器(在获取数据之前对数据做一些加工处理)

axios.interceptors.response.use(function(res){
    //res是axios所包装的数据,包含data,headers,status,statusText
    //在这里对返回的数据进行处理
    return res;
},function(err){
    //处理响应的错误信息
})

 

使用响应拦截器后调用接口中.then得到的数据就是实际数据

axios.interceptors.response.use(function(res){
    //在这里对返回的数据进行处理
    var data = res.data
    return data;        //使用后调用接口中then得到的数据就是实际数据
},function(err){
    //处理响应的错误信息
})

 

推荐阅读