【发布时间】:2019-07-17 15:56:58
【问题描述】:
我们在应用程序中遇到了一个非常奇怪的行为。
我们有一个在 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 中使用的相同标头。请求在后端成功解析,我' m 接收文件)
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",
任何帮助都会很棒。调试了很多小时都没有成功:/
【问题讨论】:
标签: node.js react-native networking multipartform-data fetch-api