Multer + React + Nodejs Axios 请求

Multer + React + Nodejs Axios request

axiosPost请求

// 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 是我在 req.body 中想要的,头像是我在 req.file 中使用 multer 在后端收到的,但我收到的是 req.file 与图像,但我的 req.body 中没有任何内容(只是一个空对象)

这是我在节点中的路由器

router.post(
  "/",
  upload.single("avatar"),
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    console.log(req.body);
      }
    );

我认为你的路线在路线文件中是/api/profile

您没有显示您的 header profileData

应该是这样的

const profileData = { headers: { 'content-type': 'multipart/form-data' } }

然后您可以像之前那样向服务器请求。

尝试使用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' });
      });
  }
}