首页 / 编程 axios通过cdn引入使用小计

axios通过cdn引入使用小计

原创 分类: 编程 2023-3-2 10:02 阅读量:1099
Axios 是一个简单的基于 promise 实现的 HTTP 客户端,适用于浏览器和 node.js。 Axios 在具有非常可扩展的接口的小包中提供了一个简单易用的库。今天我们用axios实现几种常用的请求...

一、引入axios.js

https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js

二、使用axios.js发送请求

1、发送Get请求(url传参)
axios.get('url?params1=xxxx')
  .then(function (res) {
    // 请求成功返回
    console.log(res);
  })
  .catch(function (err) {
    // 请求失败返回
    console.log(err);
  })
  .then(function () {
    // 不管成功失败都会执行,可以用来关闭加载效果等
  });
2、发送Get请求(非url传参)
axios.get('url',{
    params: {
         params1: xxxx
       }
  })
  .then(function (res) {
    // 请求成功返回
    console.log(res);
  })
  .catch(function (err) {
    // 请求失败返回
    console.log(err);
  })
  .then(function () {
    // 不管成功失败都会执行,可以用来关闭加载效果等
  });
3、发送Post请求(默认headers)
axios.post('url?params1=xxxx',{data})
  .then(function (res) {
    // 请求成功返回
    console.log(res);
  })
  .catch(function (err) {
    // 请求失败返回
    console.log(err);
  })
  .then(function () {
    // 不管成功失败都会执行,可以用来关闭加载效果等
  });
4、发送Post请求(指定headers)
axios.post('url?params1=xxxx',{data},{headers:{}})
  .then(function (res) {
    // 请求成功返回
    console.log(res);
  })
  .catch(function (err) {
    // 请求失败返回
    console.log(err);
  })
  .then(function () {
    // 不管成功失败都会执行,可以用来关闭加载效果等
  });