Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multer + React + Nodejs Axios request

Axios Post request

// Create profile
export const createProfile = (profileData, avatar, history) => dispatch => {
  dispatch(clearErrors());
  const image = new FormData();
  image.append("avatar", avatar, avatar.name);
  axios
    .post("/api/profile", image, profileData)
    .then(res => history.push("/dashboard"))
    .catch(err =>
      dispatch({
        type: GET_ERRORS,
        payload: err.response.data
      })
    );
};

Edit ---> Axios post request second attempt

// Create profile
export const createProfile = (profileData, avatar, history) => dispatch => {
  dispatch(clearErrors());
  const image = new FormData();
  image.append("avatar", avatar, avatar.name);
  image.append("user", profileData, profileData.username);
  axios
    .post("/api/profile", image)
    .then(res => history.push("/dashboard"))
    .catch(err =>
      dispatch({
        type: GET_ERRORS,
        payload: err.response.data
      })
    );
};

profileData is what i want in the req.body and avatar is what i receive in req.file in my back-end with multer, but what i receive is the req.file with the image but nothing in my req.body(Just an empty object)

This is my router in node

router.post(
  "/",
  upload.single("avatar"),
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    console.log(req.body);
      }
    );
like image 498
Daniel Daza Avatar asked Nov 23 '25 21:11

Daniel Daza


1 Answers

Try to implement in following way using FormData

handleSubmit(e)
{
  e.preventDefault();
  const err = this.validate();
  if (!err) {
    var formData = {
      category: this.state.category,
      course: this.state.course,
    };
    const { category, course } = this.state;
    let fd = new FormData();
    fd.append('Test', this.state.testFile, this.state.testFile.name);
    fd.append('category', category);
    fd.append('course', course);
    console.log(fd);
    axios({
      method: 'post',
      url: 'http://localhost:7777/api/uploadTest',
      data: fd,
    })
      .then((response) => {
        if (response.data == 'Success') {
          alert('Test has been Added..!!');
        }
        else {
          alert('Something went wrong');
          this.setState({ category: '' });
        }
        // this.setState({success:'Alert: '+response.data});
      })
      .catch((e) => {
        console.error(e);
        this.setState({ success: 'Alert: Something went wrong' });
      });
  }
}
like image 108
Jagdeesh Kumar Avatar answered Nov 25 '25 09:11

Jagdeesh Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!