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)
    })
### Axios 基础用法教程 Axios 是一种基于 Promise 的 HTTP 庢客户端,支持浏览器和 Node.js 环境。它被广泛用于前端开发中的 AJAX 请求操作,并受到 React 和 Vue 官方推荐[^2]。 #### 1. 安装 Axios 可以通过多种方式安装 Axios: - 使用 npm 进行安装: ```bash npm install axios ``` - 使用 bower 进行安装: ```bash bower install axios ``` - 如果不想通过包管理工具安装,也可以直接引入 CDN 脚本: ```html <script src="https://unpkg.com/axios/dist/axios.min.js"></script> ``` 以上三种方式均可完成 Axios 的环境准备[^4]。 #### 2. 发送 GET 请求 GET 请求通常用来获取数据。以下是发送 GET 请求的一个简单例子: ```javascript // 发起一个简单的 GET 请求 axios.get('https://jsonplaceholder.typicode.com/posts') .then(response => { console.log(response.data); // 打印返回的数据部分 }) .catch(error => { console.error('Error:', error); }); ``` 上述代码会向指定 URL 发起请求并打印响应数据。 #### 3. 发送 POST 请求 POST 请求一般用于提交表单或者上传数据。下面是一个使用 POST 方法的例子: ```javascript // 发起一个带有参数的 POST 请求 axios.post('https://jsonplaceholder.typicode.com/posts', { title: 'foo', body: 'bar', userId: 1 }) .then(response => { console.log(response.data); // 输出新创建的对象 }) .catch(error => { console.error('Error:', error); }); ``` 此示例展示了如何传递 JSON 数据到服务器。 #### 4. 配置请求选项 可以为每次请求设置额外的配置项,比如超时时间、自定义头信息等: ```javascript axios({ method: 'get', url: 'https://jsonplaceholder.typicode.com/posts', timeout: 5000, // 设置超时时间为 5 秒钟 headers: { 'Authorization': 'Bearer YOUR_ACCESS_TOKEN' } }) .then(response => { console.log(response.data); }); ``` 这里设置了 `timeout` 参数以及添加了一个授权头部字段[^3]。 #### 5. 处理错误情况 当网络异常或其他问题发生时,应该妥善处理这些错误情形: ```javascript axios.get('/error-url') // 故意访问不存在的接口来触发错误 .then(function (response) { console.log(response); }) .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code that falls out of the range of 2xx console.log(error.response.status); } else if (error.request) { // The request was made but no response was received console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error Message:', error.message); } }); ``` 这段代码演示了不同类型的错误捕获逻辑。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值