首页 > 其他分享 >Axios

Axios

时间:2024-08-17 20:26:45浏览次数:8  
标签:axios console 请求 data Axios config response

1.Axios
1.1 异步请求发展史

1.1.1 传统的Ajax
传统的Ajax请求是基于XMLHttpRequest(XHR)对象。可以直接使用。但 是使用起来配置较为麻烦,实际开发中使用非常少,在MVC时代通常使用的 是JQuery-Ajax。相对于传统的Ajax现在使用更多的是Fetch请求。

1.1.2 JQuery-Ajax
JQuery-Ajax在前端JQuery时,因为JQuery的强大兼容性在项目开发中 $Ajax使用非常广泛,需要引入JQuery库,其底层原理也是对传统的Ajax,XHR对象进行封装。但是在前端框架MVVC时代,例如使用vue搭建项目, 如果再继续使用$Ajax就还需再单独引入JQuery重量级1w+代码量的库是 得不偿失的。所以针对于框架的网络请求应运而生。

1.1.3 Axios
在Vue1.0时代,官方推出了Vue-resource,其体积相对于JQuery小得多,但是在Vue2.0时代官方宣布不再更新,那么继续使用Vue-resource就会存在版本无法匹配问题。因此在Vue2.0时代开始,官方推荐使用axios作为新一代的Ajax库。axios其优点:在浏览器中发送XMLHttpRequest请求、在node中发送http请求、支持Promise API、拦截请求和相应、转换请求和响应数据等

1.2 安装方法
使用 cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>

使用 npm:npm install axios

1.3 axios的格式

axios(config)
axios({
 key:value,
  ...
  key:value
}).then(function(res){
  console.log(res);
}).catch(err=>{
  console.log(err);
})

1.3.1请求配置项:config的详细配置参数
下面是创建请求时可用的配置选项,注意只有 url 是必需的。
如果没有指定 method,请求将默认使用 get 方法

  // `url` 是用于请求的服务器 URL
  url: "/user",
  // `method` 是创建请求时使用的方法
  method: "get", // 默认是 get
  // `headers` 是即将被发送的自定义请求头
  headers: {"X-Requested-With": "XMLHttpRequest"},
  // `params` 是即将与请求一起发送的 URL 参数
  // 必须是一个无格式对象(plain object)或 URLSearchParams 对象
  params: {
    ID: 12345
  },
  // 在没有设置 `transformRequest` 时,必须是以下类型之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 浏览器专属:FormData, File, Blob
  // -data和params的区别:
//params是用来携带请求参数的,它以key-value的形式放在URL后面,是一个对象。
//data是用来携带请求数据的,它以key-value的形式放在请求体中,是一个对象。
//axios默认使用JSON格式发送请求,所以如果你使用data发送请求,请确保服务器能够处理JSON格式的数据
  data: {
    firstName: "Fred"
  },
    // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
    // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
  baseURL: "https://some-domain.com/api/",
    // `transformRequest` 允许在向服务器发送前,修改请求数据
    // 只能用在 "PUT", "POST" 和 "PATCH" 这几个请求方法
  transformRequest: [function (data) {
  // 对 data 进行任意转换处理
  return data;
}],
  // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
  transformResponse: [function (data) {
  // 对 data 进行任意转换处理
  return data;
}],
  // `paramsSerializer` 是一个负责 `params` 序列化的函数
  // (e.g. https://www.npmjs.com/package/qs, https://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: "brackets"})
  },
  // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
  // 如果请求花费了超过 `timeout` 的时间,请求将被中断
  timeout: 1000,
      // `withCredentials` 表示跨域请求时是否需要使用凭证
  withCredentials: false, // 默认的
    // `adapter` 允许自定义处理请求,以使测试更轻松
    // 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
  adapter: function (config) {
},
  // `auth` 表示应该使用 HTTP 基础验证,并提供凭据
  // 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
  auth: {
    username: "janedoe",
    password: "s00pers3cret"
  },
  // `responseType` 表示服务器响应的数据类型,可以是 "arraybuffer", "blob", "document", "json", "text", "stream"
  responseType: "json", // 默认的
      // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
      xsrfCookieName: "XSRF-TOKEN", // default
    // `xsrfHeaderName` 是承载 xsrf token 的值的 HTTP 头的名称
    xsrfHeaderName: "X-XSRF-TOKEN", // 默认的
    // `onUploadProgress` 允许为上传处理进度事件
    onUploadProgress: function (progressEvent) {
  // 对原生进度事件的处理
},
  // `onDownloadProgress` 允许为下载处理进度事件
  onDownloadProgress: function (progressEvent) {
    // 对原生进度事件的处理
  },
  // `maxContentLength` 定义允许的响应内容的最大尺寸
  maxContentLength: 2000,
      // `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject  promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
      validateStatus: function (status) {
      return status &gt;= 200 &amp;&amp; status &lt; 300; // 默认的
},

  // `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目
  // 如果设置为0,将不会 follow 任何重定向
  maxRedirects: 5, // 默认的
      // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
      // `keepAlive` 默认没有启用
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),
    // "proxy" 定义代理服务器的主机名称和端口
    // `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
    // 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。
    proxy: {
      host: "127.0.0.1:5000",
      port: 9000,
      auth:  {
        username: "mikeymike",
        password: "rapunz3l"
  }
},
// `cancelToken` 指定用于取消请求的 cancel token
// (查看后面的 Cancellation 这节了解更多)
cancelToken: new CancelToken(function (cancel) {
 })

1.3.2响应结构:then中response信息

.then(function(response){
  console.log(response);
  // `data` 由服务器提供的响应
  console.log(response.data);
  // `status`  HTTP 状态码
  console.log(response.status);
  // `statusText` 来自服务器响应的 HTTP 状态信息
  console.log(response.statusText);
  // `headers` 服务器响应的头
  console.log(response.headers);
  // `config` 是为请求提供的配置信息
  console.log(response.config);
})

1.3.3错误处理

.catch(function (error) {
  if (error.response) {
    // 请求已发出,但服务器响应的状态码不在 2xx 范围内
    console.log(error.response.data);
    console.log(error.response.status);
    console.log(error.response.headers);
  } else {
    // Something happened in setting up the request that triggered an Error
    console.log('Error', error.message);
  }
  console.log(error.config);
});

1.4 简化写法
格式:

•  axios(config) ====== axios.request(config)
•  axios.get(url[, config])
•  axios.delete(url[, config])
•  axios.head(url[, config])
•  axios.post(url[, data[, config]])
•  axios.put(url[, data[, config]])
•  axios.patch(url[, data[, config]])

案例展示:
1、axios(config)请求方式:
axios接收一个对象,在对象中使用键值对方式写入配置信息,get请求下,默认method可以不写

2、axios.request(config)请求方式: 与axios(config)写法一致

3、axios.get(url[, config])请求方式 :限定method为get请求

  1. 表单提交
    若:<input type="text"/>,则v-model收集的是value值,用户输入的就是value值。
    若:<input type="radio"/>,则v-model收集的是value值,且要给标签配置value值。
    若:<input type="checkbox"/>
    1.没有配置input的value属性,那么收集的就是checked(勾选 or 未勾选,是布尔值)
    2.配置input的value属性:
    (1)v-model的初始值是非数组,那么收集的就是checked(勾选 or 未勾选,是布尔值)
    (2)v-model的初始值是数组,那么收集的的就是value组成的数组
    备注:v-model的三个修饰符:
    lazy:失去焦点再收集数据
    number:输入字符串转为有效的数字
    trim:输入首尾空格过滤
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <script src="./js/vue.js"></script>
    <script src="./js/axios.min.js"></script>
</head>
<body>
    <div id="app">
        <form>
            账号:<input type="text" v-model.trim="user.userCode"><br/><br/>
            密码:<input type="password" v-model="user.userPwd"><br/><br/>
            性别:<input type="radio" v-model="user.userSex" value="男">男
                 <input type="radio" v-model="user.userSex" value="女">女<br/><br/>
            爱好:<input type="checkbox" v-model="user.userHobby" value="看书">看书
                 <input type="checkbox" v-model="user.userHobby" value="睡觉">睡觉
                 <input type="checkbox" v-model="user.userHobby" value="游泳">游泳
            地址:<select v-model="user.address">
                    <option value="shanghai">上海</option>
                    <option value="北京">北京</option>
                    <option value="天津">天津</option>
                </select>
            <br/><br/>
            其他信息:
            <textarea v-model.lazy="user.other"></textarea> <br/><br/>
            <input type="checkbox" v-model="user.userAgree">阅读并接受<a href="http://www.atguigu.com">《用户协议》</a>
            <button @click="submitUser($event)">提交</button>
        </form>
    </div>
    <script>
        new Vue({
            el:"#app",
            data(){
                return {
                    user:{
                        userCode:"",
                        userPwd:"",
                        userSex:"",
                        address:"",
                        other:"",
                        userAgree:"",
//userHobby:[]数组不能以参数的形式传递
                    }
                }
            },
            methods:{
                submitUser(event){
                   event.preventDefault();//阻止默认的点击事件执行
                    console.log(this.user)
                    axios({
                        url:"getVueForm.action",
                        method:"POST",
                        params:this.user
                    }).then((result)=>{
//注意表单提交事件会导致页面刷新
console.log(result.data.messageStr)
alert(result.data.messageStr)
                    })
}
            }
        });
    </script>
</body>
</html>

2.文件上传
异步文件上传文件依然需要Mulitpart/from-data
2.1用js的formData对象上传
页面:
<input class="file" name="file" type="file" @change="update"/>
Axios处理

methods: {
    update(e){
        let file = e.target.files[0];
        let param = new FormData(); //创建form对象
        param.append('file',file);//通过append向form对象添加数据
        console.log(param.get('file')); //FormData私有类对象,访问不到,可以通过get判断值是否传进去
        let config = {
            headers:{'Content-Type':'multipart/form-data'} //这里是重点,需要和后台沟通好请求头,Content-Type不一定是这个值
        }; //添加请求头
        axios.post('upload',param,config)
            .then(response=>{
                console.log(response.data);
            })
    }
}

3.form表单的文件上传
页面

<form>
    <input type="text" value="" v-model="name" placeholder="请输入用户名">
    <input type="text" value="" v-model="age" placeholder="请输入年龄">
    <input type="file" @change="getFile($event)">
    <button @click="submitForm($event)">提交</button>
</form>

处理:

data: {
    name: '',
    age: '',
    file: ''
},
methods: {
    getFile(event) {
        this.file = event.target.files[0];
        console.log(this.file);
    },
    submitForm(event) {
        event.preventDefault();//阻止默认的点击事件执行
        let formData = new FormData();
        formData.append('name', this.name);
        formData.append('age', this.age);
        formData.append('file', this.file);
        let config = {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }
        axios.post('upload', formData, config).then(function (response) {
            if (response.status === 200) {
                console.log(response.data);
            }
        })
    }
}

标签:axios,console,请求,data,Axios,config,response
From: https://www.cnblogs.com/llhcmbs/p/18364922

相关文章

  • Axios请求使用params参数导致后端获取数据嵌套
    问题重述:首先看前端的axios请求这里我使用params参数将data数据传给后端letdata=JSON.stringify(this.posts);axios.post("/blog_war_exploded/insertPost",{params:{data:data......
  • 5.vue中axios封装工程化
    vue工程化中axios封装视频演示地址:https://www.bilibili.com/video/BV121egeQEHg/?vd_source=0f4eae2845bd3b24b877e4586ffda69a通常我们封装需要封装request.js基础的发送请求工具类,再根据业务封装service类,service类是具体业务的接口封装,在页面上直接调用的是servive类......
  • 鸿蒙HarmonyOS NEXT:使用axios方法请求实时天气数据
    通过axios方法请求高德天气查询api,实现获取实时天气数据,接下来是实现步骤:模块导入与数据准备:通过以下语句导入了必要的模块和数据:importaxios,{AxiosResponse,AxiosError}from'@ohos/axios'//导入axiosimport{cities}from'./tools/citys';//调用事先存好的城......
  • axios访问后端,及后端返回前端报错跨域问题
    packagecom.example.demo.test.config;importorg.springframework.util.StringUtils;importjavax.servlet.*;importjavax.servlet.annotation.WebFilter;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjav......
  • 使用 Axios 下载文件并更新进度条
    使用Axios下载文件并更新进度条使用axios的onDownloadProgress回调函数实现下载文件,并更新下载进度条。示例代码import{ElMessage}from"element-plus";importaxiosfrom"axios";importtype{AxiosResponse,AxiosProgressEvent}from"axios";import{baseUrl......
  • axios报错Module not found: Error: Package path ./lib/helpers/buildURL is not exp
    node12使用axios报错:Modulenotfound:Error:Packagepath./lib/helpers/buildURLisnotexportedfrompackageimportbuildURLfrom"axios/lib/helpers/buildURL";import{merge}from"axios/lib/utils";一、原因:对于importaxiosfrom‘./lib/......
  • Vue3+vite+axios+.net api 配置
    exportdefaultdefineConfig({plugins:[vue()],resolve:{alias:{"@":fileURLToPath(newURL("./src",import.meta.url)),},},server:{host:"0.0.0.0",open:true,//启动项目自动弹出浏览器port:&qu......
  • AJAX - 利用XML和Promise封装简易版axios,了解axios底层原理
     AJAX原理-XMLHttpRequest定义:XMLHttpRequest(XHR)对象用于与服务器交互。通过XMLHttpRequest可以在不刷新页面的情况下请求特定URL,获取数据。这允许网页在不影响用户操作的情况下,更新页面的局部内容。XMLHttpRequest 在 AJAX 编程中被大量使用。关系:axios内部采用......
  • Element学习(axios异步加载数据、案例操作)(5)
    1、这次学习的是上次还未完成好的恶element案例,对列表数据的异步加载,并渲染展示。——>axios来发送异步请求(1)(2)在vue当中安装axios(注意在当前的项目目录,并且安装完之后再将项目重启一下)(3)这里我用到数据的url地址为:https://mock.apifox.cn/m1/3128855-0-default/emp/list......
  • Nuxt3 axios封装 使用axios接口请求
    一、先安装axiosnpminstalladdaxios封装请求request.ts文件importaxiosfrom'axios'import{ElMessage,Message}from"element-plus"import{getToken}from'./token.js'constservice=axios.create({baseURL:'/api',//......