无法使用Node.js和React Native将文件上传到服务器

时间:2019-02-23 20:40:43

标签: node.js react-native networking multipartform-data fetch-api

我们在应用程序中面临一个非常奇怪的行为。

我们在Heroku上运行了一个Node.js服务器。我们的客户端是一个React本机应用程序,试图将文件发送到我们的服务器。

前端代码:

import ImagePicker from "react-native-image-picker";

class MyComponent extends React.Component {

...    

handleGallery = () => {
  ImagePicker.showImagePicker(pickerOptions, response => {

  const { uri, type, fileName } = response;
  const data = new FormData();

  data.append("data", { uri, type, name: `photo.${fileName}` });

  this.submitMultpart(data)
    .then(res => {
      console.log(res);
    })
    .catch(err => {
      console.log(err);
    });
   }
  });
 };

 submitMultpart = formData => {
  return new Promise((resolve, reject) => {
  const URL = "https://example.com/api/upload";

  const options = {
    method: "POST",
    body: formData,
    headers: {
      Accept: "application/json",
      "Content-Type": "multipart/form-data; boundary=6ff46e0b6b5148d984f148b6542e5a5d",
    }
  };

  fetch(URL, options)
    .then(res => {
      console.log(res);
      resolve(res);
    })
   .catch(err => {
      console.log(JSON.stringify(err));
      reject(err);
   });
 });
};
}

后端代码:

const multiparty = require("multiparty");

app.post("/api/upload", async (req, res) => {
  const form = new multiparty.Form();

  form.parse(req, async (error, _fields, files) => {
    if (error) {
      console.error(error);
      return res.status(500).json({ success: false });
    }

    // Do some stuff here


    return res.status(200).json({ success: true });
  });
});

我在node.js控制台中遇到的错误是:

{
  BadRequestError: stream ended unexpectedly
  at Form.<anonymous>(/app/node_modules / multiparty / index.js: 759: 24)
  at Form.emit(events.js: 194: 15)
  at finishMaybe(_stream_writable.js: 641: 14)
  at endWritable(_stream_writable.js: 649: 3)
  at Form.Writable.end(_stream_writable.js: 589: 5)
  at IncomingMessage.onend(_stream_readable.js: 629: 10)
  at Object.onceWrapper(events.js: 277: 13)
  at IncomingMessage.emit(events.js: 194: 15)
  at endReadableNT(_stream_readable.js: 1103: 12)
  at process._tickCallback(internal / process / next_tick.js: 63: 19) message: 'stream ended unexpectedly'
}

p.s:标头由FETCH api正确设置。我们正在后端接收它们。

p.s2:使用邮递员,我能够将文件发送到服务器(使用与FETCH api中使用的标头相同的标头。在后端成功解析了请求,我正在接收文件)

p.s3:我要发送的文件很小,因此似乎文件的大小在这里不是问题。

p.s4:我在请求的标头中使用了随机边界,因为没有它,我会收到此错误:

{ 
  BadRequestError: content-type missing boundary
  at Form.parse (/app/node_modules/multiparty/index.js:180:21)
  at app.post (/app/routes/api/personalDocumentRoute.js:12:10)
  at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
  at next (/app/node_modules/express/lib/router/route.js:137:13)
  at admin.auth.verifyIdToken.then.firebaseUser (/app/middlewares/requireFirebaseLogin.js:26:14)
  at process._tickCallback (internal/process/next_tick.js:68:7) message: 'content-type missing boundary' 
}

其他信息:

package.json

"react": "16.6.3",
"react-native": "0.58.3",

任何帮助都将是惊人的。大量时间的调试未成功:/

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题。

尝试一下:

  headers: { 
        'Accept': 'multipart/form-data',
        'Content-Type': 'multipart/form-data',
      }