axios的所有用法

本文介绍了axios库中常用的HTTP请求方法:get、post、put和delete的参数传递方式,包括通过URL、params选项、URLSearchParams及json格式。同时,解析了axios响应结果的结构,如data、headers、status和statusText,并提及axios的请求和响应拦截器的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

axios常用的四个方法:

  1. get:查询数据
  2. post:添加数据
  3. put:修改数据
  4. delete:删除数据

1.get传递参数

①通过URL传递参数

第一种:通过问号进行传参

  axios.get('http://localhost:3000/axios?id=123').then(function(ret){
      console.log(ret.data)
    })

获取参数用query.id

app.get('/axios', (req, res) => {
  res.send('axios get 传递参数' + req.query.id)
})

第二种:直接加参数进行传参

    axios.get('http://localhost:3000/axios/123').then(function(ret){
      console.log(ret.data)

获取参数用params.id

app.get('/axios/:id', (req, res) => {
  res.send('axios get (Restful) 传递参数' + req.params.id)
})

改变的两处细节:
在这里插入图片描述
注:
如果使用直接传参,在接收参数时要加上“:id”

②通过params选项传递参数

        this.axios.get('http://127.0.0.1:8080/new/findSomeNews',{
            params:{
                typeId:1,
                start:0,
                number:7
            }
        }).then(res=>{
            if(res.data.code == 1){
                this.list = res.data.data;
                console.log(this.list);
            }

        });

2.delete传递参数(同get相同)

3.post传递参数

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

    axios.post('http://localhost:3000/axios', {
      uname: 'lisi',
      pwd: 123
    }).then(function(ret){
      console.log(ret.data)
    })

使用body.xxx获取参数:

app.post('/axios', (req, res) => {
  res.send('axios post 传递参数' + req.body.uname + '---' + req.body.pwd)
})

②通过URLSearchParams传递参数(表单形式传递参数)

   var params = new URLSearchParams();
    params.append('uname', 'zhangsan');
    params.append('pwd', '111');
    axios.post('http://localhost:3000/axios', params).then(function(ret){
      console.log(ret.data)
    })

4.put传递参数

    axios.put('http://localhost:3000/axios/123', {
      uname: 'lisi',
      pwd: 123
    }).then(function(ret){
      console.log(ret.data)
    })

axios的响应结果

  1. data:实际相应回来的数据
  2. headers:响应头信息
  3. status:响应状态码
  4. statusTxet:响应状态信息

axios拦截器

1.请求拦截器

//添加一个请求拦截器
    axios.interceptors.request.use(function(config) {
    //请求发出之前设置一些信息
      console.log(config.url)
      config.headers.mytoken = 'nihao';
      //这里必须返回config,这样才能够完成拦截器的功能
      return config;
    }, function(err){
     //这里处理响应的错误信息
      console.log(err)
    })

2.响应拦截器

    axios.interceptors.response.use(function(res) {
      // 在这里对返回的数据进行处理
      //res不是真正的数据,data才是真正的数据
      var data = res.data;
      return data;
    }, function(err){
    //这里处理响应的错误信息
      console.log(err)
    })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值