提示信息

Axios用法示例

天仇 已关注

Axios 是一个基于 Promise 的 HTTP 客户端,可以用来发送 GET、POST 和其他类型的 HTTP 请求。这是一些基本用法示例:

首先,你需要在项目中安装 axios:

  1. npm install axios --save

或者:

  1. yarn add axios

然后,在文件中导入 axios 并进行使用:

  1. import axios from 'axios';
  2. // 发送 GET 请求
  3. axios.get('https://api.example.com/items')
  4. .then(response => {
  5. // 处理成功响应
  6. console.log(response.data);
  7. })
  8. .catch(error => {
  9. // 处理错误响应
  10. console.log(error);
  11. });
  12. // 发送 POST 请求
  13. axios.post('https://api.example.com/items', {
  14. item: 'New item'
  15. })
  16. .then(response => {
  17. console.log(response.data);
  18. })
  19. .catch(error => {
  20. console.log(error);
  21. });

以下是如何设置全局配置:

  1. axios.defaults.baseURL = 'https://api.example.com';
  2. axios.defaults.headers.common['Authorization'] = 'Bearer token';

也可以对单独的请求设置配置:

  1. axios.get('/user', {
  2. params: {
  3. ID: 12345
  4. },
  5. headers: {
  6. 'Authorization' : 'Bearer token'
  7. }
  8. })
  9. .then(function (response) {
  10. console.log(response.data);
  11. })
  12. .catch(function (error) {
  13. console.log(error);
  14. });

以上就是 axios 的基本用法,你可以访问其官方文档查看更多详细的信息和高级用法。

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
天仇 关注 已关注

最近一次登录:2023-12-14 21:40:05   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图