Home > Net >  FormData not working with Axios Post request - MERN react Js
FormData not working with Axios Post request - MERN react Js

Time:07-14

I've been trying to make a post request to my server(Node Js Mongodb which runs on localhost too). Axios.post works properly on the client code, however when i try to use formData it doesn't. I can't seem to find any reason why it's not working. It leaves no error on the console(which makes it more frustrating). Here is the client code:

someone pls point me to what I might be doing wrong.

import React, { useState } from 'react'
import Axios  from 'axios'
export default function InputData() {
    const [inputName, setInputName] = useState("")
    const [inputAge, setInputAge] = useState(0)
    const [inputEmail, setInputEmail] = useState("")
    const [userImage, setUserImage] = useState("")
    const [info,setInfo] = useState("")
    
    var bodyFormData = new FormData();
    bodyFormData.append('name', inputName);
    bodyFormData.append('age', inputAge);
    bodyFormData.append("email", inputEmail)

    const createUser = () => {
        Axios.post("http://localhost:3008/createUser",
             bodyFormData , { headers: { 'Content-Type': 'multipart/form-data' } }).then(function (response) {
            //handle success
            console.log(response);
        }).catch(function (response) {
            //handle error
            console.log(response);
        });

     
  }
  return (
      <div>
          
          <form onSubmit={createUser} encType="multipart/form-data">
              <div>
                  <input type="text" placeholder='enter name' value={inputName} width={400} onChange={(e) => setInputName(e.target.value)} /><br/>
                  <input type="number" placeholder='enter age' width={400} value={inputAge} onChange={(e) => setInputAge(e.target.value)} /><br/>
              <input type="email" placeholder='enter e-mail' width={400} value={inputEmail} onChange={(e) => setInputEmail(e.target.value)} /><br />
                  
                  <button>Submit</button>
              </div>
</form>
          
          </div>
  )
}

axios: "^0.27.2", react: "^18.2.0"

CodePudding user response:

I think you will receive all the data from the event [createUser method] on submitting the form, Try removing the header If you still have problem try as below, If you still have the problem check the server side Post method Params

let data = { name: inputName, age: inputAge, email: inputEmail }
Axios.post("http://localhost:3008/createUser",data )
.then(function (response) { console.log(response);  })
.catch(function (response) { console.log(response);  });

CodePudding user response:

Couple of points:

  1. You're probably not seeing any errors (output) in the console because you're submitting the form. You can change your onSubmit handler to include enter image description here
  2. You should add method=post to your form
  • Related