我们正在尝试将图像上传到使用expressjs / multer来解析multipart/form-data
输入的NodeJS服务器。不幸的是,我们遇到类似的TypeError:
TypeError: Cannot read property 'path' of undefined
at /var/www/app/services/media/multer.js:41:31
at Immediate.<anonymous> (/var/www/app/node_modules/multer/lib/make-middleware.js:52:37)
at Immediate.immediate._onImmediate (timers.js:590:18)
at tryOnImmediate (timers.js:543:15)
at processImmediate [as _immediateCallback] (timers.js:523:5)
[nodemon] app crashed - waiting for file changes before starting.
在调查之后,我们发现这个后端错误意味着multer.js没有向file
添加req
字段,从而导致req.file.path ===> TypeError
在稍后的图像处理中。
使用Wireshark嗅探数据包,我们发现我们上传的方法是发送路径而不是文件的内容。
这里是ReactJS代码(使用superagent):
selectPhotoTapped() {
ImagePicker.showImagePicker({
title: 'Select Image'
}, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled photo picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
var promise = new Promise(function(resolve, reject) {
request
.put(Environment.BASE_URL + '/media/img/')
.attach('upload', response.path, response.fileName)
.field('usertype', 'Barber')
.field('name', 'profilePic')
.field('description', 'Holla')
.field('type', 'test:barber:haircut')
.end(function(err, res) {
if (err) {
reject(err);
} else {
resolve(res);
}
});
}).then((response) => {
console.log(response);
alert("HERE");
response.json();
}).then((responseData) => {
alert("Succes " + responseData)
}).catch((error) => {
alert("ERROR " + error)
console.log(error);
});
}
});
}
这是我们的后端multer代码:
var storage = Multer.diskStorage({
destination: path.join(__dirname, '../../../', config.media.img),
filename: generate_filename
});
var multer = Multer({
storage: storage,
fileSize: 25 * 1024 * 1024,
fileFilter: filter
});
router.put('/media/img/', auth.authenticate, multer.single('upload'), media.img.put);
所以问题是:当我们使用attach
方法时,为什么superagent只发送路径?我们在后端的mocha测试中测试了完全相同的superagent代码,一切都很好。那么为什么React和Node之间存在差异呢?