使用 nodejs express 解析表单数据

parsing form-data with nodejs express

我正在使用 axios 从 reactjs 应用程序发送表单数据,如下面的代码所述。快递配置正确,但 req.body 仍然是空的。在这种情况下我做错了什么?

import bodyParser from 'body-parser';

app.use(busboy());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

反应

export const createAd = (token, ad) => async (dispatch) => {
  const headers = {
    headers: {
      "content-type": "multipart/form-data",
      Authorization: `Bearer ${token}`,
    },
  };


  for (var pair of ad.entries()) {
    console.log(pair[0] + ', ' + pair[1]);
  }

  const response = await api
    .post("/ads/create/", ad, headers)
    .catch((error) => {
      dispatch({ type: constants.PUSH_ERROR, payload: error });
    });
  if (response && response.status === 201) {
    dispatch({ type: constants.CREATE_AD, payload: response.data.ad });
  }
};

api 端点

export const createAd = async (req, res) => {
    try {
        const bb = busboy({ headers: req.headers });

        bb.on('file', async (name, file, info) => {
            console.log("*Uploading files")
            const { filename, encoding, mimeType } = info;
            var saveTo = 'public/ads/' + filename
            file.pipe(fs.createWriteStream(saveTo));
            file.resume();
        });
        bb.on('finish', () => {
            console.log('Upload complete');
            res.writeHead(200, { 'Connection': 'close' });
            res.end("That's all folks!");
        });

        console.log(req.body) // empty body here {}
        res.status(201).send({ message: "Ad created.", ad: {} });


    } catch (error) {
        res.status(400).send(error)
        console.error(error)
    }
}

使用 multiparty 库你也可以做到这一点。

app.post('/ads/create/', function (req, res) {
var form_data = new multiparty.Form();
form_data.parse(req, function(err, fields, files) {
    // fields fields fields
});
})