Axios POSTed FormData在服务器端具有空主体

时间:2018-09-04 13:54:53

标签: node.js express file-upload axios

这是客户端代码。数据不为空,文件已正确上传。

export function addGame(data) {
    return dispatch => {
    const formData = new FormData();
    formData.append("game.cover", data.gameCover[0]);
    formData.append("game.title", data.gameTitle);
    formData.append("game.price", data.gamePrice);
    formData.append("game.description", data.description);

    return axios.post(apiUrl + "/games/add", formData).then(res => {
      dispatch({ type: ADD_GAME, payload: res.data.game });
    });
  };
}

这是服务器端

  router.post("/add", auth, async (req, res) => {
  const body = await req.body;
  console.log(body);
  let formErrors = [];
  if (!body.gameTitle) formErrors.push("Game title is required.");
  if (!body.description) formErrors.push("Description is required.");
  if (!body.gamePrice) formErrors.push("Price is required.");

  if (formErrors.length) res.status(400).send({ success: false, formErrors });
  else {
     let gameCoverFileName;
     if (!fileUpload(req, gameCoverFileName))
       formErrors.push("Failed to upload file");

const result = await gameModel.create({
  title: body.gameTitle,
  cover: gameCoverFileName,
  price: body.gamePrice,
  description: body.description
});
if (result)
  res.status(201).send({
    success: true,
    game: {
      gameTitle: result.title,
      gameCover: gameCoverFileName,
      gamePrice: result.price,
      description: result.description
    }
  });
} });

我的身体空了

1 个答案:

答案 0 :(得分:0)

您需要另外处理多部分表单数据。例如使用multiparty:

const multiparty = require("multiparty");

router.post("/add", auth, async (req, res) => {
    try {
        const parse = function (req) {
            return new Promise(function(resolve, reject) {
                const form = new multiparty.Form()
                form.parse(req, function(err, fields, files) {
                    !err ? resolve([fields, files]) : reject(err)
                })
            })
        }
        const [body] = await parse(req)
        console.log(body)
    } catch (err) {
        console.log(err)
    }
    res.json("ok")
})