node.js - 来自表单数据POST的Nodejs空请求正文

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

我有一个照片应用程序 (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);

最佳答案

您似乎忘记设置应用程序来解析作为 form-data 发送的数据。如果你 checkout 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!')
});

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

关于node.js - 来自表单数据POST的Nodejs空请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48602592/

相关文章:

javascript - 我可以使用 HummuJS 修改现有 PDF 文件中的框吗?

node.js - React 和 NodeJS 如何协同工作?

node.js - Angular,未找到图像(GET 404),但运行 ng build 后显示图像

node.js - 我无法使用nodejs在openshift中上传图像

node.js - 如何将自定义数据添加到 Mongoose 模式?

javascript - 如果用户之前使用过该操作,如何让 Dialogflow 代理向用户打招呼?

javascript - node.js/socket.io 消失变量

javascript - React-Native:AsyncStorage.getItem 不起作用。我已经从react-native-community安装了AsyncStorage

javascript - 无法查看列表的最后一项

node.js - 不执行使用 multer 库的测试