Home > Enterprise >  Axios FormData is sending null values to backend
Axios FormData is sending null values to backend

Time:05-23

I am building a MERN Application in which I am sending user name and email from react to Node.js The formData is printing correctly but when I use axios to send the data to backend(localhost:5000/register) is is giving me an null values(req.body = undefined). Please help me solve this.

server.js

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

router.get('/home',(req,res)=>{
  res.send('This is home page 1');
});

router.post('/register',async(req, res) => {
  console.log('reached Backend');
  const name = req.body.name;
  const email = req.body.email;
  console.log(req.body);
  // try{
  //     const user = new collection1({name,email});
  //     await user.save();
  //     res.status(201).json({message: "registered succussfully"});
  //   }
  //   catch(err) {
  //     console.log(err);
  //   }
  });

  app.use("/",router);
async function initServer(){
  const PORT = process.env.PORT || 5000;
  app.listen(PORT,()=>
  console.log(`express server is running on the  port ${PORT}`))
}


initServer();

Front-end App.js

const App= () => {
  const [user, setUser] = useState({
    name:"",
    email:"",
  });
  let name, value;
  const handleInput = (e) => {
    name = e.target.name;
    value = e.target.value;

    setUser({...user,[name]:value});
}
const handleSubmit=async(e) =>{
  e.preventDefault()
  const formData = new FormData();
  console.log("username",user.name);
  formData.append('name', user.name)
  formData.append('email', user.email)
  for (var key of formData.entries()) {
    console.log(key[0]   ', '   key[1]);
}

  console.log("trying th reach backend");
  await axios.post("http://localhost:5000/register", formData,{
    headers: {'Content-Type': 'multipart/form-data' }
  }).then(res => {
      console.log('res:',res);
      window.alert("Registration  Successful");
  }).catch((err)=>{
      console.log("Failed to reach bachend")
       console.error(err.response.data);
  })
}

  return (
    <div className="App">
      <form method = "POST" encType="multipart/form-data">
        <input type="text" name="name" value={user.name} id="name" onChange={handleInput}></input>
        <input type="email" name="email" value={user.email} id="email" onChange={handleInput}></input>
        <input type="submit" name="App" id="App" value="App" onClick={handleSubmit} ></input>
      </form>

CodePudding user response:

If you are receiving JSON in the backend why do you send FormData? You can try using express-formidable or express-form-data

I'm not 100% sure about this 'cause I usually send the data through JSON.

BTW: Body parser is deprecated. Try using express.json().

CodePudding user response:

You have two problems:

headers: {'Content-Type': 'multipart/form-data' }

You are missing the mandatory boundary parameter. You also have no way of knowing what it needs to be. Omit that and let the browser infer the correct content-type from the FormData object.

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

You don't have a middware capable of parsing multipart form data.

Add one.


Alternatively, since you aren't dealing with files, stop trying to use multipart form data.

Replace FormData with URLSearchParams and post URL encoded form data which bodyParser.urlencoded can handle.

  • Related