ylb-axios

axios是一个基于 promise 的 HTTP 库,可在浏览器和 node.js 的HTTP客户端中。
特性:

  • 从浏览器中创建 XMLHttpRequest
  • 从 node.js 发出 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换JSON数据
  • 客户端支持防止 CSRF/XSRF

1、使用方式

 npm使用方式

npm install axios		

 cdn方式

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

 使用本地文件

<script src="js/axios.min.js"></script>

 在vue项目的main.js文件中引入axios

import axios from 'axios'
Vue.prototype.$axios = axios

 在组件中使用axios

<script>
	export default {
		mounted(){
			this.$axios.get('/goods.json').then(res=>{
				console.log(res.data);
			})
		}
	}
</script>

2、使用axios发起请求

  • get:获取数据,请求指定的信息,返回实体对象
  • post:向指定资源提交数据(例如表单提交或文件上传)
  • put:更新数据,从客户端向服务器传送的数据取代指定的文档的内容
  • patch:更新数据,是对put方法的补充,用来对已知资源进行局部更新
  • delete:请求服务器删除指定的数据

2.1 get请求url中传递参数

服务器controller

@GetMapping("/api/v1/user/query")
public SysUser getUser2(Integer uid){
  SysUser user = new SysUser();
  user.setId(uid);
  user.setLoginPassword("hello");
  user.setName("lisi");
  user.setPhone("1360000000");
  return user;
}

前端:
在项目根目录下创建js目录,目录中添加axios.min.js文件
准备页面:testAxios.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="js/axios.min.js"></script>
</head>
<body>
    <button onclick="f1()">发起get请求例子1</button>
    <script>

    </script>
</body>
</html>

f1请求

<body>
    <button onclick="f1()">发起get请求例子1</button>
    <script>
        function f1(){
            let url="http://localhost:8000/ylb/api/v1/user/query?uid=1021";
            axios.get(url).then( (resp)=>{
                console.log("请求成功,服务响应数据="+resp)
            }).catch((err)=>{
                console.log("请求失败:"+err)
            })
        }
    </script>
</body>

f2请求: 使用axios配置项 params,指定get请求参数列表

<button onclick="f2()">发起get请求例子2</button>

function f2(){
    let url="http://localhost:8000/ylb/api/v1/user/query";
    axios.get(url,{
        params:{
            uid:2126
        }
    }).then( (resp)=>{
        console.log("请求成功,服务响应数据="+resp)
        console.dir(resp)
    }).catch((err)=>{
        console.log("请求失败:"+err)
    })
}

2.2 post请求,参数名=值&参数名=值方式传递请求参数

服务器:

@PostMapping("/api/v1/users")
public SysUser getUser2(String name,String passwd){
  SysUser user = new SysUser();
  user.setId(1001);
  user.setLoginPassword(passwd);
  user.setName(name);
  user.setPhone("1360000000");
  return user;
}

前端

<button onclick="f3()">发起post请求例子1</button>
function f3(){
    let url="http://localhost:8000/ylb/api/v1/users";
    axios.post(url,"name=lisi&passwd=123456").then( (resp)=>{
        console.log("请求成功,服务响应数据="+resp)
        console.dir(resp)
    }).catch((err)=>{
        console.log("请求失败:"+err)
    })
}

2.3 请求参数是json格式, 后端使用@RequestBody

服务器

public class Person {
  private String name;
  private String passwd;
  // set | get
}
@PostMapping("/api/v1/person")
public Person getPerson(@RequestBody Person person){
  System.out.println("person="+person);
  return person;
}

前端 : 使用axios的配置项,发送请求

<button onclick="f4()">发起post请求例子2</button>
function f4(){
    let url="http://localhost:8000/ylb/api/v1/person";
    axios({
        url:url,
        method: 'post',
        data:{
            'name':'zhangsan',
            'passwd':'111222'
        }
    }).then( (resp) =>{
        console.log("resp="+resp)
    }).catch( (error)=>{
        console.log("错误="+error)
    })
}

完整的配置项:

{
  // `url` 是用于请求的服务器 URL
  url: '/user',

  // `method` 是创建请求时使用的方法
  method: 'get', // 默认是 get

  // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
  // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest` 允许在向服务器发送前,修改请求数据
  // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
  // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
  transformRequest: [function (data) {
    // 对 data 进行任意转换处理

    return data;
  }],

  // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
  transformResponse: [function (data) {
    // 对 data 进行任意转换处理

    return data;
  }],

  // `headers` 是即将被发送的自定义请求头
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params` 是即将与请求一起发送的 URL 参数
  // 必须是一个无格式对象(plain object)或 URLSearchParams 对象
  params: {
    ID: 12345
  },

  // `paramsSerializer` 是一个负责 `params` 序列化的函数
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `data` 是作为请求主体被发送的数据
  // 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
  // 在没有设置 `transformRequest` 时,必须是以下类型之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 浏览器专属:FormData, File, Blob
  // - Node 专属: Stream
  data: {
    firstName: 'Fred'
  },

  // `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 >= 200 && status < 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',
    port: 9000,
    auth: : {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken` 指定用于取消请求的 cancel token
  // (查看后面的 Cancellation 这节了解更多)
  cancelToken: new CancelToken(function (cancel) {
  })}

3、请求方法的别名

  • axios.get(url[, config])
  • axios.delete(url[, config])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]])

4、axios返回数据

响应结构,是一个json

{
  // `data` 由服务器提供的响应
  data: {},

  // `status` 来自服务器响应的 HTTP 状态码
  status: 200,

  // `statusText` 来自服务器响应的 HTTP 状态信息
  statusText: 'OK',

  // `headers` 服务器响应的头
  headers: {},

  // `config` 是为请求提供的配置信息
  config: {}
}
<button onclick="f6()">应答数据</button>

function f6(){
    let ins = axios.create({
        baseURL:'http://localhost:8000/ylb',
        timeout:10000
    })
    ins.get("/api/v1/user/query?uid=1001")
        .then( (resp)=>{
            console.log("resp="+resp.data)
            console.log("resp="+resp.status)
            console.log("resp="+resp.statusText)
            console.log("resp="+resp.data.id)
            console.log("resp="+resp.data.name)
            console.log("resp="+resp.data.phone)
        }).catch((error)=>{
            console.log("错误="+error)
            console.dir(error);//error是一个错误对象
            console.log(error.response.data);
            console.log(error.response.data.error);
           console.log(error.response.status);
       })
}

5、拦截器

分成请求拦截器和响应拦截器
请求拦截器:在发起请求之前执行,可以对请求内容做修改,比如增加参数,设置请求头等等。
应答拦截器:服务器返回结果,axios的then之前先执行。可以对应答内容对预先的处理。

拦截器使用例子

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="js/axios.min.js"></script>
</head>

<body>
    <button onclick="f1()">请求拦截器</button>
    <script>
        //请求拦截器
        axios.interceptors.request.use(function(config){
            //请求之前做些什么:比如改变请求参数,设置timeout等等
            console.log("======请求之前=====")
            config.url = config.url+"&name=lisi";
            return config;
        },function (error) {
            // 对请求错误做些什么
            return Promise.reject(error);
        })

        //应答拦截器
        axios.interceptors.response.use(function(response){
            //对响应做什么
            console.log("=====响应数据了=======")
            return response;

        },function(error){
            // 对响应错误做点什么
            return Promise.reject(error);
        })


        function f1(){
            let url="http://localhost:8000/ylb/api/v1/user/query?uid=1021";
            axios.get(url).then( (resp)=>{
                console.log("请求成功,服务响应数据="+resp)
            }).catch((err)=>{
                console.log("请求失败:"+err)
            })
        }


    </script>
</body>

6、全局的 axios 默认值

axios.defaults.baseURL = ‘https://api.example.com’;
axios.defaults.timeout=50000;
axios.defaults.headers.common[‘Authorization’] = AUTH_TOKEN;
axios.defaults.headers.post[‘Content-Type’] = ‘application/x-www-form-urlencoded’;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值