AJAX请求(axios篇)

发布于:2024-04-18 ⋅ 阅读:(26) ⋅ 点赞:(0)

目录

一、axios介绍

1.概念

2.功能

3.好处

二、axios用法

1.安装方法

2.GET方法

 3.POST方法

4.执行多个并发请求

5.axios API

6.请求方法的别名

7.async/await异步请求

三、axios实例

四、总结


一、axios介绍

1.概念

AJAX是“Asynchronous JavaScript and XML”的缩写,它是一种用于创建交互式网页应用程序的技术。AJAX允许在不重新加载整个网页的情况下,异步地向服务器发送请求并获取数据。这使得网页可以更加动态和交互性,而不会中断用户的操作。

Axios是一个基于Promise的HTTP客户端,用于浏览器和Node.js环境,它可以在前端和后端进行HTTP请求。它的设计简单、易于使用,提供了丰富的功能和选项来处理HTTP请求和响应。

2.功能

  1. 发送HTTP请求: Axios支持发送各种类型的HTTP请求,包括GET、POST、PUT、DELETE等。

  2. Promise API: Axios使用Promise API来处理异步请求,使得代码更加清晰和易于理解。

  3. 拦截器: 可以使用拦截器对请求和响应进行全局的处理,比如在请求发送之前添加公共的请求头,或者在响应返回后进行数据处理。

  4. 取消请求: Axios提供了取消请求的功能,可以在需要时取消正在进行的请求,避免不必要的网络请求。

  5. 错误处理: 可以方便地处理请求过程中可能发生的错误,包括网络错误、超时等。

3.好处

  1. 简单易用: Axios提供了简洁清晰的API,易于学习和使用。

  2. 跨平台: 可以在浏览器和Node.js环境中使用,适用于前后端分离的开发模式。

  3. 功能丰富: 提供了丰富的功能和选项,包括拦截器、取消请求、错误处理等,满足了各种复杂场景下的需求。

  4. 广泛支持: Axios被广泛应用于各种前端框架和库中,比如React、Vue.js等,成为了业界标准之一。

二、axios用法

1.安装方法

使用 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

使用 bower:

$ bower install axios

使用 yarn:

$ yarn add axios

使用方法:

Vue.axios.get(api).then((response) => {
  console.log(response.data)
})

this.axios.get(api).then((response) => {
  console.log(response.data)
})

this.$http.get(api).then((response) => {
  console.log(response.data)
})

2.GET方法

我们可以简单的读取数据:

axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

 也可以读取JSON 数据

const app = {
  data() {
    return {
      info: 'Ajax 测试!!'
    }
  },
  mounted () {
    axios
      .get('https://www.runoob.com/try/ajax/json_demo.json')
      .then(response => (this.info = response))
      .catch(function (error) { // 请求失败处理
        console.log(error);
    });
  }
}
 
Vue.createApp(app).mount('#app')

使用 response.data 读取 JSON 数据:

<div id="app">
  <h1>网站列表</h1>
  <div
    v-for="site in info"
  >
    {{ site.name }}
  </div>
</div>
<script type = "text/javascript">
const app = {
  data() {
    return {
      info: 'Ajax 测试!!'
    }
  },
  mounted () {
    axios
      .get('https://www.runoob.com/try/ajax/json_demo.json')
      .then(response => (this.info = response.data.sites))
      .catch(function (error) { // 请求失败处理
        console.log(error);
    });
  }
}
 
Vue.createApp(app).mount('#app')
</script>

GET 方法传递参数格式如下:

// 直接在 URL 上添加参数 ID=12345
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
 
// 也可以通过 params 设置参数:
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

 3.POST方法

axios.post('https://api.example.com/data', {
    key: 'value'
  })
  .then(response => {
    console.log('Response:', response.data);
  })
  .catch(error => {
    console.error('Error posting data:', error);
  });

POST 方法传递参数格式如下:

axios.post('/user', {
    firstName: 'Fred',        // 参数 firstName
    lastName: 'Flintstone'    // 参数 lastName
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

4.执行多个并发请求

function getUserAccount() {
  return axios.get('/user/12345');
}
 
function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成
  }));

5.axios API

axios(config)
// 发送 POST 请求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
//  GET 请求远程图片
axios({
  method:'get',
  url:'http://bit.ly/2mTM3nY',
  responseType:'stream'
})
  .then(function(response) {
  response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
axios(url[, config])
// 发送 GET 请求(默认的方法)
axios('/user/12345');

6.请求方法的别名

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]])

7.async/await异步请求

async function fetchData() {
  try {
    const response = await axios.get('https://api.example.com/data');
    console.log(response.data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

fetchData();

三、axios实例

1.使用jsonplaceholder提供的一个公开的API来获取一些示例数据。我们发送了一个GET请求到https://jsonplaceholder.typicode.com/posts,并在控制台中打印出返回的数据。

// 引入Axios
import axios from 'axios';

// 使用Axios发送GET请求获取数据
axios.get('https://jsonplaceholder.typicode.com/posts')
  .then(response => {
    // 打印返回的数据
    console.log('Response:', response.data);
  })
  .catch(error => {
    // 处理错误
    console.error('Error fetching data:', error);
  });

2.注册

// 引入Axios
import axios from 'axios';

// 用户注册信息
const userData = {
  username: 'example_user',
  email: 'example@example.com',
  password: 'example_password'
};

// 使用Axios发送POST请求进行用户注册
axios.post('https://jsonplaceholder.typicode.com/posts', userData)
  .then(response => {
    // 打印注册成功后返回的用户信息
    console.log('User registered successfully:', response.data);
  })
  .catch(error => {
    // 处理注册过程中可能发生的错误
    console.error('Error registering user:', error);
  });

在这个示例中,我们创建了一个包含用户注册信息的对象userData,然后使用Axios发送了一个POST请求到https://jsonplaceholder.typicode.com/posts。在这个示例中,我们使用jsonplaceholder提供的一个模拟API来模拟用户注册过程。在这个示例中,我们使用jsonplaceholder提供的一个模拟API来模拟用户注册过程。

如果注册成功,服务器会返回注册用户的信息,并在then回调函数中打印出来;如果注册过程中发生错误,错误信息会在catch回调函数中进行处理。

这个示例演示了如何使用Axios发送POST请求并处理响应,你可以根据自己的需求来发送不同类型的请求,并对返回的数据进行相应的处理。Axios提供了丰富的功能和选项,可以满足各种不同场景和需求。

四、总结

Axios是一个流行的基于Promise的HTTP客户端库,用于浏览器和Node.js环境中进行HTTP请求。下面是Axios的一些关键特点和优势:

  1. 简单易用: Axios提供了清晰简洁的API,易于学习和使用,使得发送HTTP请求变得更加简单和高效。

  2. 功能丰富: 支持发送各种类型的HTTP请求,包括GET、POST、PUT、DELETE等,同时提供了丰富的功能和选项,比如拦截器、取消请求、错误处理等。

  3. Promise API: Axios使用Promise API来处理异步请求,使得代码更加清晰易懂,可以轻松处理异步操作。

  4. 跨平台: 可以在浏览器和Node.js环境中使用,适用于前后端分离的开发模式。

  5. 拦截器: 可以使用拦截器对请求和响应进行全局的处理,比如在请求发送之前添加公共的请求头,或者在响应返回后进行数据处理。

  6. 错误处理: 提供了方便的错误处理机制,可以处理请求过程中可能出现的各种错误,包括网络错误、超时等。

  7. 广泛支持: 被广泛应用于各种前端框架和库中,成为了业界标准之一,同时也适用于Node.js后端开发。

总的来说,Axios是一个功能强大、易用的HTTP客户端库,为开发者提供了便捷的方式来处理AJAX请求,使得开发交互式的Web应用程序变得更加简单和高效。