初面网初面网

axios

基于promise封装的http库

// get
axios.get("http://localhost:3000/users", {
  params: {
    name: "tom",
    age: 18
  }
})
  .then(res=>{
    console.log(res)
    console.log(res.data)
  })
  .catch(err=>{
    console.log("err", err)
  })

// post
axios.post("http://localhost:3000/users", {
  name: "tom",
  age: 18
})
  .then(res=>{
    console.log(res)
    console.log(res.data)
  })
  .catch(err=>{
    console.log("err", err)
  })

// put
axios.put("http://localhost:3000/users/1", {
  age: 18
})
  .then(res=>{
    console.log(res)
    console.log(res.data)
  })
  .catch(err=>{
    console.log("err", err)
  })

// patch
axios.patch("http://localhost:3000/users/1", {
  age: 28
})
  .then(res=>{
    console.log(res)
    console.log(res.data)
  })
  .catch(err=>{
    console.log("err", err)
  })

// delete
axios.delete("http://localhost:3000/users/1")
  .then(res=>{
    console.log(res)
    console.log(res.data)
  })
  .catch(err=>{
    console.log("err", err)
  })

拦截器

关键词:interceptors、request、response

分成前置拦截器,后置拦截器(响应拦截器)。前置拦截器会在发请求前再做处理,后置拦截器会在请求后再做处理。

// 前置拦截器
axios.interceptors.request.use(function(config){
  return config;
},function(error){
  return Promise.reject(error);
})

// 响应拦截器
axios.interceptors.response.use(function(config){
  return config;
},function(error){
  return Promise.reject(error);
})

中断器

中断前一个请求

const controller = new AbortController();

axios.get('/user',{
  signal: controller.signal
}).then(function(response){

});

// cancel the request
controller.abort()

更新于 2025/2/26