首页 > 解决方案 > 将文件/表单数据发布到节点服务器失败。错误: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)

标签: node.jsfetchmulter

解决方案


由于body-parser,这个问题已经解决了。它总是使用body-parse来解析表单数据,当我搜索这个错误时,错误是'Body:entity-parse-failed',我突然意识到这就是重点。然后我在'body-parser'之前写'multer',图片/文件可以成功上传。


推荐阅读