{"pageProps":{"post":{"title":"How to submit form data in post request using axios","excerpt":"Learn to submit form data in HTTP post request using axios","date":"2021-08-01T00:00:00.000Z","slug":"axios-post-form-data","author":{"name":"Suraj Sharma","picture":""},"content":"\n
\n\nIn this tutorial, you will learn how you can send submitted form data in a post request in React using axios.\n\n
\n\nConsider we have a `` component with two input fields and a submit button.\n\n
\n```jsx\nimport React from 'react';\nimport axios from 'axios';\n\nconst LoginForm = () => {\n \n const [formValue, setformValue] = React.useState({\n email: '',\n password: ''\n });\n\n const handleSubmit = (event) => {\n // we will fill this in the coming paragraph\n }\n\n const handleChange = (event) => {\n setformValue({\n ...formValue,\n [event.target.name]: event.target.value\n });\n }\n\n return (\n
\n

Login Form

\n \n \n \n Login\n \n \n )\n};\n\nexport default LoginForm;\n```\n\n
\n
\n\nTo create a form-data we will use [FormData Web API](https://developer.mozilla.org/en-US/docs/Web/API/FormData), which stores fields and its values as key-value pairs.\n\nNext, make a HTTP POST request in axios with `loginFormData` passed as a `data` property value in the axios request object.\n\n
\n```javascript\nconst handleSubmit = async() => {\n // store the states in the form data\n const loginFormData = new FormData();\n loginFormData.append(\"username\", formValue.email)\n loginFormData.append(\"password\", formValue.password)\n\n try {\n // make axios post request\n const response = await axios({\n method: \"post\",\n url: \"/api/login\",\n data: loginFormData,\n headers: { \"Content-Type\": \"multipart/form-data\" },\n });\n } catch(error) {\n console.log(error)\n }\n}\n```\n\n
\n
\n\n**Related Solutions**\n\n- [How to send a delete request in axios](/blog/axios-delete-request)\n\n- [How to loop through an array of objects in React](/blog/for-loop-in-react)\n\n- [How to deploy a create React app to Github pages for free](/blog/deploy-react-app-to-github-pages)\n\n- [How to submit a login form in React using React hook](/blog/react-submit-login-form)\n\n- [How to set HTTP headers in Axios](/blog/axios-set-headers)\n\n
","coverImage":{"url":"/images/cover-image.png"},"url":"axios-post-form-data","hashtags":"#react #axios"}},"__N_SSG":true}