axios请求

可传参数

axios({
        //请求方式 get post delete put
        method:"",
        //请求地址
        url:"",
        //query 参数
        params:{

        },
        // body参数
        data:{

        },
        //请求头 一般是用来指定请求传参格式
       
        //请求中没有 data参数 所以headers content-type 默认为 content-type: "application/json;charset=UTF-8"
        // headers: {
        //   // 'content-type': 'application/json;charset=UTF-8'(默认)
        //   "Content-Type": "application/x-www-form-urlencoded",
        // 'content-type':"multipart/form-data"
        // },
        
        headers:{},
      }).then(function(res){
        console.log(res)
      })
    }

get请求

query

如何区分是不是get请求中的query请求?
在这里插入图片描述
第一种 params方式

// params 对象内写形式
getInstructorById1(id) {
      axios({
        method: "get",
        url: "http://localhost:8080/instructor/getInstructorById",
        params: {
          id: id,
          //如果 key value名字相同可简写 例如 id:id可以写为 id
        },
      }).then(function (res) {
        console.log(res);
      });
    },
//params 对象外写形式
    getInstructorById3(id) {
      const params = {
        id: id,
        //如果 key value名字相同可简写 例如 id:id可以写为 id
      };
      axios({
        method: "get",
        url: "http://localhost:8080/instructor/getInstructorById",
        params,
      }).then(function (res) {
        console.log(res);
      });
    },

第二种 拼接方式

 //?a="a"&b="b" 拼接形式
 getInstructorById2(id) {
      axios({
        method: "get",
        url: `http://localhost:8080/instructor/getInstructorById?id=${id}`,
        //与下面两种写法都可以
        // url: "http://localhost:8080/instructor/getInstructorById?id=" + id,
      }).then(function (res) {
        console.log(res);
      });
    },

path

如何区分是Get中的path形式
在这里插入图片描述

//path
    getById1(id) {
      axios({
        method: "get",
        // url: "http://localhost:8080/instructor/getById/" + id,
        //两种写法都可以
        url: `http://localhost:8080/instructor/getById/${id}`,
      }).then(function (res) {
        console.log(res);
      });
    },

post请求

query

如何区分是post query请求
在这里插入图片描述
第一种 params

//post params
    add1(id) {
      axios({
        method: "post",
        url: "http://localhost:8080//instructor/add",
        params: {
          id: id,
          name: "jhj",
        },
      }).then((res) => {
        console.log(res);
      });
    },

第二种 formdata

 add2(id) {
      const params = {
        id,
        name: "jhj",
      };
      axios({
        method: "post",
        url: "http://localhost:8080//instructor/add",
        data:params,
        headers:{
          'content-type':"multipart/form-data"
        }
      }).then((res) => {
        console.log(res);
      });
    },
add3(id) {
      const data=new FormData();
      data.append("name","jhj")
      data.append("id",id)
      axios({
        method: "post",
        url: "http://localhost:8080//instructor/add",
        data:data,
      }).then((res) => {
        console.log(res);
      });
    },

body

如何区分 是body post请求
在这里插入图片描述

addbody(id) {
      axios({
        method: "post",
        url: `http://localhost:8080/instructor/addbody`,
        data: {
          id: id,
          name: "jhj",
        },
        //请求中没有 data参数 所以headers content-type 默认为 content-type: "application/json;charset=UTF-8"
        // headers: {
        //   // 'content-type': 'application/json;charset=UTF-8' 默认
        //   // "Content-Type": "application/x-www-form-urlencoded",
        //   // "content-type":"multipart/form-data"
        // },
      }).then(function (res) {
        console.log(res);
      });
    },

header

在这里插入图片描述

putheader(id) {
      axios({
        method: "post",
        url: `http://localhost:8080/instructor/putheader`,

        //自定义header
        headers: {
          // 'content-type': 'application/json;charset=UTF-8'
          // "Content-Type": "application/x-www-form-urlencoded",
          // "content-type":"multipart/form-data"
          myheader: id,
        },
      }).then(function (res) {
        console.log(res);
      });
    },

delete

在这里插入图片描述

 //deleted params
    del1(id) {
      axios({
        method: "delete",
        url: "http://localhost:8080/instructor/delete",
        params: {
          id: id,
          //如果 key value名字相同可简写 例如 id:id可以写为 id
        },
      }).then(function (res) {
        console.log(res);
      });
    },

put

put query

在这里插入图片描述

put(id) {
      axios({
        method: "put",
        url: `http://localhost:8080/instructor/put`,
        params: {
          id: id,
          name: "jhj",
        },
      }).then(function (res) {
        console.log(res);
      });
    },

put body

在这里插入图片描述

 putbody(id) {
      axios({
        method: "put",
        url: `http://localhost:8080/instructor/putbody`,
        data: {
          id: id,
          name: "jhj",
        },
      }).then(function (res) {
        console.log(res);
      });
    },

综合

在这里插入图片描述

all(id) {
      axios({
        method: "post",
        url: `http://localhost:8080/instructor/all/${id}`,
        params: {
          ids:id
        },
        data: {
          id,
          name: "jhj",
        },
        //自定义header
        headers: {
          // 'content-type': 'application/json;charset=UTF-8'
          // "Content-Type": "application/x-www-form-urlencoded",
          // "content-type":"multipart/form-data"
          myheader: id,
        },
      }).then(function (res) {
        console.log(res);
      });
    },

作者声明

如有问题,欢迎指正!
### Axios 请求使用方法 Axios 是一个基于 Promise 的 HTTP 客户端,可以在浏览器和 Node.js 中使用。其主要特点是可以拦截请求和响应、取消请求以及自动转换 JSON 数据。 #### 安装 Axios 为了在 Vue 项目中使用 Axios,可以通过 npm 或 yarn 进行安装: ```bash npm install axios --save ``` 或者 ```bash yarn add axios ``` 这一步骤确保了 Axios 成功集成到开发环境中[^1]。 #### 基础配置与引入 完成安装后,在项目的入口文件或公共工具类中引入 Axios: ```javascript import axios from 'axios'; ``` 接着可以根据需求设置全局默认值,比如 API 地址前缀、超时时间等: ```javascript // 设置默认URL前缀 axios.defaults.baseURL = 'https://api.example.com'; // 设置请求超时时间为5秒 axios.defaults.timeout = 5000; ``` 以上操作简化了后续调用中的重复配置工作[^3]。 #### 发送 GET 和 POST 请求 对于简单的数据获取场景,可以直接利用 `get` 方法发起网络请求;而当涉及到提交表单或其他复杂的数据交互,则推荐采用 `post` 方式: ```javascript // 发起GET请求并处理成功/失败情况 axios.get('/user?ID=12345') .then(function (response) { console.log(response.data); }) .catch(function (error) { console.error(error); }); // 发起POST请求携带JSON格式body体 axios.post('/submit', { title: 'foo', body: 'bar' }) .then(function (response) { console.log(response.status); // 打印状态码 }) .catch(function (error) { console.error('Error:', error.message); }); ``` 上述代码片段展示了基本的同步流程控制逻辑[^2]。 #### 处理并发请求 如果需要同时发出多个异步请求,并等待它们全部完成后才执行下一步动作,可借助于 `Promise.all()` 函数来实现这一点: ```javascript function getUserAccount() { return axios.get('/user/account'); } function getUserPermissions() { return axios.get('/user/permissions'); } Promise.all([getUserAccount(), getUserPermissions()]) .then((results) => { const accountInfo = results[0].data; const permissionList = results[1].data; // 继续其他业务逻辑... }).catch(err => { console.warn(`One of the requests failed ${err}`); }); ``` 这段例子说明了如何高效管理多条独立但关联的任务链路。 #### 拦截器的应用 通过定义自定义中间件函数作为拦截处理器,能够在每次发送请求前后及接收到服务器回应之后实施特定行为,例如统一添加认证令牌至头部字段或是集中捕获异常状况: ```javascript // 添加请求拦截器 axios.interceptors.request.use(config => { config.headers['Authorization'] = localStorage.getItem('token'); // 将 token 放入 header 中 return config; }, error => { return Promise.reject(error); }); // 添加响应拦截器 axios.interceptors.response.use(response => response, error => { if (!error.response || !error.response.data){ alert("连接不上服务器"); return Promise.reject(error); } switch (error.response.status) { case 401: window.location.href="/login"; break; default: return Promise.reject(error); } }); ``` 此部分强调了增强应用程序健壮性的策略之一——合理运用拦截机制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值