How to send maltipart/formdata from react to nodejs?

Viewed 24

Hi I am new in MERN development world. I am trying develop my first MERN APP, till text input from browser I have created. Now I am stucked at the file input.

File field is working fine at frontend but in api the file field is empty but rest of the fields are working well... In browser before api call photo/ file is there but in the api req.body or req.file no data. I have used multer which is working fine.

Please help me, I trapped here.

Frontend Code

export const register = ({ name, email, password, password1, photo }) => (dispatch) => {
  // Request body
  const body = { name, email, password, password1, photo };
  /*console.log(photo); //gives the desired output...*/
  axios.post('/api/users/register', body)
  .then(function (res) {
    dispatch(returnStatus(res.data, res.status, 'REGISTER_SUCCESS'));
    dispatch({ type: IS_LOADING })
  })
  .catch(function (err) {
    dispatch(returnStatus(err.response.data, err.response.status, 'REGISTER_FAIL'))
      dispatch({
        type: REGISTER_FAIL
      });
      dispatch({ type: IS_LOADING })
  });
};

Serverside code

exports.registerUser = (upload.single("photo"), (req, res) => {
  const { name, email, password, password1 } = req.body;
  console.log(req.file,req.body);
  if(password != password1) return res.status(400).json("Passwords missmacth.");
  const result = registerSchema.validate({ name, email, password});
  if(!result.error) {

      // Check for existing user
      User.findOne({ email: email }).then((user) => {
        if (user) return res.status(400).json("User already exists");
        //New User created
        const newUser = new User({
          name,
          email,
          password,
          password1
        });

        //Password hashing
        bcrypt.genSalt(12, (err, salt) =>
          bcrypt.hash(newUser.password, salt, (err, hash) => {
            if (err) throw err;

            newUser.password = hash;
            bcrypt.hash(newUser.password1, salt, (err, hash) => {
              if (err) throw err;
  
              newUser.password1 = hash;
              // Save user
              newUser
                .save()
                .then(
                  res.json("Successfully Registered")
                )
                .catch((err) => console.log(err));
                })
          })
        );
      });
  } else {
    res.status(422).json(result.error.details[0].message);
  }

});
0 Answers
Related