Nodejs表单数据POST请求中的空请求体

9
我有一个照片应用程序(React Native),试图向nodejs express端点发出带有照片和一些元数据的POST请求。Node应用程序将照片上传到S3。使用multer,照片+ S3部分工作得非常好,但我似乎无法访问元数据,因为它是空的。客户端:React Native。
var formData = new FormData();

formData.append('photo', {
  uri: this.state.photo.uri,
  name: 'image.jpg',
  type: 'image/jpeg',
});

formData.append('meta', {
  title: "the best title",
  lat: this.state.lat,
  long: this.state.long
});

const config = {
  method: 'POST',
  body: formData,
  headers: {
    'Accept': 'application/json',
  }
}

console.log(config) // I see both photo and meta in the formData
fetch("http://localhost:5001/upload", config)
  .then((responseData) => {
    console.log('awesome, we did it');
  })
  .catch(err => {
    console.log(err);
  });
}

服务器:Nodejs + multer + s3

const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
multerS3 = require('multer-s3');

var AWS = require('aws-sdk');
var fs =  require('fs');

var s3 = new AWS.S3();
var myBucket = 'my-bucket';
var myKey = 'jpeg';

var upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: myBucket,
    key: function (req, file, cb) {
      console.log(file);
      cb(null, file.originalname);
    }
  })
});

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

app.post('/upload', upload.array('photo', 1), (request, response, next) => {
  // The upload to s3 works fine
  console.log(request.body); // I cannot see anything in the body, I only see { meta: '' }
  response.send('uploaded!')
});

exports.app = functions.https.onRequest(app);
3个回答

2

看起来您忘记设置应用程序以解析发送的数据为form-data。如果您查看bodyparser文档,您可以发现您需要启用form-data解析:

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

所以配置应该像这样:

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

app.post('/upload', upload.array('photo', 1), (request, response, next) => 
{
  // The upload to s3 works fine
  console.log(request.body); // I cannot see anything in the body, I only see { meta: '' }
  response.send('uploaded!')
});

通过这个设置,您的代码应该能够按预期运行。

非常感谢。我按照你的建议进行了更新,但不幸的是仍然没有运气。 - user2755635

1
尝试删除'Content-Type': 'multipart/form-data'multipart/form-data类型需要设置boundaries
您设置Content-Type头会覆盖boundary部分,这应该由浏览器自动创建。请注意保留HTML标记。

谢谢。我已经按照您的建议进行了更新,但不幸的是仍然没有成功。 - user2755635

0

在这里找到了解决方法here。它不是我怀疑的node或multer的问题,而是我错误地格式化了表单数据。

需要这样:

formData.append('meta.title', "the best title")
formData.append('meta.lat', this.state.latitude)
formData.append('meta.long', this.state.longitude)

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