Express.js multer看不到文本字段只有文件

时间:2016-06-05 21:23:56

标签: ajax express reactjs multer

当我使用AJAX请求将multipart / form-data表单发送到包含图片和3个文本字段的服务器时,multer只处理图像,但没有文本字段。如何从那里提取文本字段? FormData constructor

  handleSubmit = () => {
    let formData = new FormData(this.refs.productSubmit);
    this.props.submitProduct(formData);
  }

Form

<form action="javascript:void(0);" onSubmit={this.handleSubmit} ref="productSubmit">
  <label> Название </label>
  <input className={'form-control'} type="text" name="name" />
  <label> Цена </label>
  <input className={'form-control'} type="text" name="price" />
  <label> Описание </label>
  <input className={'form-control'} type="text" name="description" />
  <label> Изображение </label>
  <input className={'form-control'} type="file" name="picture" style={{height: '100%'}}/>
  <hr/>
  <button className={'btn btn-warning btn-lg'} bsSize={'small'} type="submit"> Добавить </button>
</form>

Async action creator with AJAX call inside

export function submitProduct(formData) {
  return function(dispatch) {
    return (
      $.ajax({
        url: '/addproduct',
        method: 'post',
        cache: false,
        contentType: false,
        processData: false,
        data: formData,
        success: data => {
          //dispatch(addedProduct());
        },
        error: (xhr, status, err) => {
          console.error(this.props.url, status, err.toString());
        }
      })
    );
  };
}

Server-side request processer

  app.post('/addproduct', isLoggedIn, isAdmin, upload.single('image'), (req, res) => {
    console.log(req);
    console.log(req.body);
    console.log(req.file);
});

但是req.body是未定义的。文件是可访问的。字段存在于有效负载请求中,我可以使用firefox devtools查看它们。如何获取文本字段?

1 个答案:

答案 0 :(得分:1)

从Express 4.0开始,您需要手动添加body-parser中间件,否则表单不会被解析,req.body将被定义。

在您的主文件中,您应该执行以下操作:

var express = require('express');
var bodyParser = require('body-parser');

var app = express();

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

// ...

module.exports = app;