Multer + React + Nodejs Axios请求

3

Axios Post请求

// 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
      })
    );
};

编辑 ---> Axios 发送 post 请求第二次尝试

// 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 是我想在后端中通过 multer 获取的 req.body 内容,而 avatar 是我通过 req.file 获取的文件。但是我在接收时只能得到带有图像的 req.file ,而在 req.body 中却什么都没有(只是一个空对象)。

这是我的 node 路由器:

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

4

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

实际上我已经尝试过这个了。// 创建个人资料 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 }) ); };但没有结果。 - Daniel Daza
我已经编辑了我的答案,因为我无法在这里编写代码,请查看编辑部分。使用formData没有得到任何结果。 - Daniel Daza
谢谢!我不知道我可以使用.append来发送文件数据。 - Omar Shishani

0

我在路由文件中将您的路由视为/api/profile

您没有显示您的头文件profileData

应该像这样:

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

然后您可以像以前一样向服务器发出请求。


使用axios时,您无需指定标题,而profileData是一个对象,函数createProfile接收所有配置文件信息。 - Daniel Daza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接