How to post data using axios Javascript




In this post, we will see how to send post data to an API endpoint using Axios

Installing Axios

To install axios, run below command.

yarn add axios

Getting the data

consider we have 2 inputs and a button, when the user clicks button we need to send the data from the inputs to the endpoint.


import React from 'react'

const App = () => {
    const [username, setUsername] = React.useState('')
    const [password, setPassword] = React.useState('')
    return (
        <>
            <input onChange={e => setUsername(e.target.value)} />
            <input onChange={e => setPassword(e.target.value)} />
            <button onClick={submit}>Submit</button>
        </>
    )
}

export default App;

Now, we can write the submit function as follows,

const submit = async () => {
        await Axios.post('http://localhost:3001', {
            username: username,
            password: password
        }).then(res => console.log(res.data)).catch(err => console.log(err))
    }

Final code will look like below,


import React from 'react'
import Axios from 'axios'

const App = () => {
    const [username, setUsername] = React.useState('')
    const [password, setPassword] = React.useState('')

    const submit = async () => {
        await Axios.post('http://localhost:3001', {
            username: username,
            password: password
        }).then(res => console.log(res.data)).catch(err => console.log(err))
    }
    return (
        <>
            <input onChange={e => setUsername(e.target.value)} />
            <input onChange={e => setPassword(e.target.value)} />
            <button onClick={submit}>Submit</button>
        </>
    )
}

export default App;