发布于 2026-01-06 5 阅读
0

在 React.js 中使用 AXIOS 发送 GET 和 POST 请求

在 React.js 中使用 AXIOS 发送 GET 和 POST 请求

大家好,我是Aya Bouchiha,今天我们将介绍如何使用axios在 react.js 中发送 POST 和 GET 请求。

Axios

axios:是一个流行的 Javascript 库,用于向 API 发出 HTTP 请求。

为什么选择 axios 而不是 fetch?

我推荐阅读 Faraz Kelhini 的这篇文章:

Axios 安装

加拿大

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

或者:

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

npm

npm i axios
Enter fullscreen mode Exit fullscreen mode

纱

yarn add axios
Enter fullscreen mode Exit fullscreen mode

凉亭

bower install axios
Enter fullscreen mode Exit fullscreen mode

使用 axios 发送 GET 请求

GET:是用于从指定服务器获取或检索数据或信息的请求。

使用 then 和 catch 的代码

import { useEffect } from 'react';
import axios from 'axios';
const App = () => {
    useEffect(() => {
        const getTodo = () => {
            axios
                .get('https://jsonplaceholder.typicode.com/todos/1')
                .then((response) => {
                    console.log(response.status);
                    console.log(response.data);
                })
                .catch((e) => console.log('something went wrong :(', e));
        };
        getTodo();
    }, []);
    return <div>GET REQUEST</div>;
};
export default App;
Enter fullscreen mode Exit fullscreen mode

安慰

200
{userId: 1, id: 1, title: "delectus aut autem", completed: false}
Enter fullscreen mode Exit fullscreen mode

使用 async 和 await 的代码

import { useEffect } from 'react';
import axios from 'axios';
const App = () => {
    useEffect(() => {
        const getTodo = async () => {
            try {
                const response = await axios.get(
                    'https://jsonplaceholder.typicode.com/todos/1',
                );
                console.log(response.status);
                console.log(response.data);
            } catch (e) {
                console.log('something went wrong :( ', e);
            }
        };
        getTodo();
    }, []);
    return <div>GET REQUEST</div>;
};
export default App;
Enter fullscreen mode Exit fullscreen mode

安慰

200
{userId: 1, id: 1, title: "delectus aut autem", completed: false}
Enter fullscreen mode Exit fullscreen mode

使用 axios 发送 POST 请求

POST:是一种用于向特定服务器发送信息或数据的请求。

axios.post(url, data, config)

使用 then 和 catch 的代码

import { useEffect } from 'react';
import axios from 'axios';
const App = () => {
    useEffect(() => {
        const postTodo = () => {
            const data = {
                title: 'drink water',
                body: 'I should drink water',
                userId: 3,
            };
            const headers = { 'header-name': 'value' };
            const config = { headers, };
            axios
                .post(
                    'https://jsonplaceholder.typicode.com/posts',
                    data,
                    config,
                )
                .then((response) => {
                    console.log(response.status);
                    console.log(response.data);
                })
                .catch((e) => console.log('something went wrong :(', e));
        };
        postTodo();
    }, []);
    return <div>POST REQUEST</div>;
};
export default App;
Enter fullscreen mode Exit fullscreen mode

安慰

201
{title: "drink water", body: "I should drink water", userId: 3, id: 101}
Enter fullscreen mode Exit fullscreen mode

使用 async 和 await 的代码

import { useEffect } from "react";
import axios from "axios";
const App = () => {
  useEffect(() => {
    const postTodo = async () => {
      const data = {
        title: "drink water",
        body: "I should drink water",
        userId: 3
      };
      const headers = { "header-name": "value" };
      const config = { headers, };
      try {
        const response = await axios.post(
          "https://jsonplaceholder.typicode.com/posts",
          data,
          config
        );
        console.log(response.status);
        console.log(response.data);
      } catch (e) {
        console.log("something went wrong!",e);
      }
    };
    postTodo();
  }, []);
  return <div>POST REQUEST</div>;
};
export default App;
Enter fullscreen mode Exit fullscreen mode

安慰

201
{title: "drink water", body: "I should drink water", userId: 3, id: 101}
Enter fullscreen mode Exit fullscreen mode

参考资料和实用资源

推荐帖子

联系方式:

祝您编程愉快!

文章来源:https://dev.to/ayabouchiha/making-get-and-post-request-using-axios-7g8