Axios 中的 Get、Post、Put、Delete

发布: (2025年12月16日 GMT+8 21:13)
2 min read
原文: Dev.to

Source: Dev.to

安装

npm

npm install axios

bower

bower install axios

yarn

yarn add axios

引入 Axios

import axios from 'axios';

Axios 基础

GET 请求

axios.get('url')
  .then((response) => {
    // handle success
    console.log(response);
  })
  .catch((error) => {
    // handle error
    console.log(error);
  });

POST 请求

axios.post('url', {
  id: 1,
  name: 'rohith'
})
  .then((response) => {
    // handle success
    console.log(response);
  })
  .catch((error) => {
    // handle error
    console.log(error);
  });

PUT 请求

axios.put('url', {
  id: 1,
  name: 'ndrohith'
})
  .then((response) => {
    // handle success
    console.log(response);
  })
  .catch((error) => {
    // handle error
    console.log(error);
  });

DELETE 请求

axios.delete('url', {
  id: 1,
})
  .then((response) => {
    // handle success
    console.log(response);
  })
  .catch((error) => {
    // handle error
    console.log(error);
  });

在 React 类组件中使用 Axios

import React, { Component } from "react";
import axios from "axios";

class AxiosRequests extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  async componentDidMount() {
    try {
      await axios({
        url: url,
        method: "GET",
      }).then((res) => {
        // handle success
        console.log(res);
      });
    } catch (e) {
      // handle error
      console.error(e);
    }
  }

  postData = async (e) => {
    e.preventDefault();
    const data = { id: 1, name: "rohith" };
    try {
      await axios({
        url: url,
        method: "POST",
        data,
      }).then((res) => {
        // handle success
        console.log(res);
      });
    } catch (e) {
      console.error(e);
    }
  };

  putData = async (e) => {
    e.preventDefault();
    const data = { id: 1, name: "ndrohith" };
    try {
      await axios({
        url: url,
        method: "PUT",
        data,
      }).then((res) => {
        // handle success
        console.log(res);
      });
    } catch (e) {
      console.error(e);
    }
  };

  deleteData = async (e) => {
    e.preventDefault();
    const data = { id: 1 };
    try {
      await axios({
        url: url,
        method: "DELETE",
        data,
      }).then((res) => {
        // handle success
        console.log(res);
      });
    } catch (e) {
      console.error(e);
    }
  };

  render() {
    return <>;
  }
}

export default AxiosRequests;

注意: async/await 是 ECMAScript 2017 的特性,Internet Explorer 及旧版浏览器不支持;使用时请谨慎。

参考文献: Axios Documentation

Back to Blog

相关文章

阅读更多 »

了解 API 及其结构

什么是 API?API 代表 Application Programming Interface(应用程序编程接口)。基本上,API 是一种……