Nodejs从表单数据POST

时间:2018-02-03 22:10:27

标签: node.js react-native multer multer-s3

我有一个照片应用程序(React Native),它试图通过照片和一些元数据向nodejs express端点发出POST请求。节点应用将照片上传到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 个答案:

答案 0 :(得分:0)

您似乎忘记设置应用程序来解析以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!')
});

使用此设置,您的代码应该按预期工作。

答案 1 :(得分:0)

尝试删除'Content-Type': 'multipart/form-data'

multipart/form-data类型需要设置boundaries

您设置Content-Type标题会覆盖boundary部分,该部分应自动由浏览器创建。

答案 2 :(得分:-1)

修复找到here。我怀疑这不是节点或闷热的问题。我错误地格式化了表单数据。

需要:

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