node.js - 将文件/表单数据发布到节点服务器失败。错误:SyntaxError: Unexpected token - 在 JSON 中的位置 0
问题描述
问题:
当我点击“选择文件”输入时,我将向服务器发送一个发布请求,正文是'formdata',将文件上传到服务器。服务器将使用“multer”包解析正文。但是请求总是在被multer解析之前失败。
#client:
<form noValidate autoComplete="off" method ="post" enctype="multipart/form-data">
<Grid item xs={12}>
<InputLabel htmlFor="files"> Attachments:</InputLabel>
<input color="default" type="file" id="files" name="selectedFiles"
onChange = {this.handleFileSelected} multiple/>
</Grid>
</form>
handleFileSelected = event => {
const formData = new FormData();
const files = event.target.files;
for (let size = 0; size < files.length; size++){
formData.append('selectedFiles',files[size]);
}
fetchServer.uploadFiles(formData)
.then(result => {
if (result.isUploaded){
console.log('upload success');
}
})
.catch(error => {
console.log(error);
});
}
#fetch:
fetchServer.uploadFiles = async (files) =>{
try{
const result = await fetch ("/upload",{
method: 'POST',
credentials:'include',
headers: {
'Content-Type': 'multipart/form-data'
},
body : files
});
return await result.json();
}
catch(e){
return Promise.reject(`upload-files-fail ( ${e} )`);
}
}
#server:
const express = require('express');
const router = express.Router();
const multer = require('multer');
const storage = multer.memoryStorage({
destination: (req,file,callback) =>{
callback(null,'');
}
});
const multipleUpload = multer({dest:'uploads/'}).array('selectedFiles',12);
router.post('/upload', multipleUpload,(req,res,next) =>{
if(err){
console.log('err...'+err);
}else{
console.log('req files: '+ req.files);
res.status(200).send({isUploaded:true});
}
});
网络:
一般的:
Request URL: http://localhost:8080/upload
Request Method: POST
Status Code: 400 Bad Request
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade
请求有效载荷:
------WebKitFormBoundaryaAAZzUX8MrAtoQDo Content-Disposition: form-data; name="selectedFiles"; 文件名="default.jpg" 内容类型:图像/jpeg
------WebKitFormBoundaryaAAZzUX8MrAtoQDo Content-Disposition: form-data; name="selectedFiles"; filename="local.jpg" 内容类型:image/jpeg
------WebKitFormBoundaryaAAZzUX8MrAtoQDo--
错误:
SyntaxError: Unexpected token - in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError (C:\Users\xxx\repo\react-app-ui\node_modules\body-
parser\lib\types\json.js:158:10)
at parse (C:\Users\xxx\repo\react-app-ui\node_modules\body-
parser\lib\types\json.js:83:15)
at C:\Users\xxx\repo\react-app-ui\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (C:\Users\xxx\repo\react-app-ui\node_modules\raw-
body\index.js:224:16)
at done (C:\Users\xxx\repo\react-app-ui\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\Users\xxx\repo\react-app-ui\node_modules\raw-
body\index.js:273:7)
at emitNone (events.js:106:13)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
解决方案
由于body-parser,这个问题已经解决了。它总是使用body-parse来解析表单数据,当我搜索这个错误时,错误是'Body:entity-parse-failed',我突然意识到这就是重点。然后我在'body-parser'之前写'multer',图片/文件可以成功上传。
推荐阅读
- r - 如何修复语义仪表板中的布局?
- python - 在基础 Tensorflow 2.0 中运行简单回归
- sql - 如何有条件地对一组数值求和
- azure-devops - 具有多个工件的 AzureDevOps 发布管道
- python - 正则表达式匹配不同的日历日期格式日期 "M{0,1,2}/D{1,2}/Y{2,4}", "Y{4}"
- python - 通过字典排序
- conv-neural-network - 在运行 deeplab 代码时运行“sh local_test.sh”命令时出现“No Module named Tensorflow”错误
- cplex - 将 'sense' 和 'rhs' 从 CPLEX 转换为 CVXPY
- php - php多维数组在html表格视图中打印
- c++ - 根据不同的硬件在任意数量的线程上分配 for 循环