DEV Community

Aya Bouchiha
Aya Bouchiha

Posted on

Making GET And POST Request Using AXIOS In React.js

Hi, I'm Aya Bouchiha, today, we'll cover sending POST and GET requests in react.js using axios.

Axios

axios: is a popular Javascript library used for making HTTP requests to an API.

Why axios instead of fetch?

I recommend reading this article by Faraz Kelhini :

Axios installation

cdn

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

Or:

<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

yarn add axios
Enter fullscreen mode Exit fullscreen mode

bower

bower install axios
Enter fullscreen mode Exit fullscreen mode

GET request using axios

GET: is a request used for getting or retrieving data or information from a specified server.

Code using then and 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

Console

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

Code using async and 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

Console

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

POST request using axios

POST: is a request that is used for sending information or data to a specific server.

axios.post(url, data, config)

Code using then and 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

console

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

Code using async and 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

console

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

References and useful Resources

Suggested Posts

To Contact Me:

Happy codding!

Discussion (3)

Collapse
marzelin profile image
Marc Ziel

You're using react in your examples so they won't work without it installed and configured. Is react really needed in a post that should talk specifically about axios?

Why do you wrap axios code inside a function instead of using it directly?

Collapse
johnmazanis profile image
John Mazanis

I used Axios in a VueJS project. It was very good choise for making GET And POST Request too.

Collapse
ayabouchiha profile image
Aya Bouchiha Author

Axios is so useful when it comes to sending requests to a server.