Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in Multer image upload: Unexpected token - in JSON at position 0, SyntaxError: Unexpected token # in JSON at position 0

Please help me to get out of this. This is my uploadRouter.js in which I am trying to upload image file from POSTMAN using multer module

const express = require('express');
const mongoose = require('mongoose');
const autheticate = require('../authenticate');
const multer = require('multer')
const bodyParser = require('body-parser');
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'public/images');
    },
    filename: (req, file, cb) => {
        cb(null, file.originalname);
    }
});
const imageFileFilter = (req, file, cb) => {
    if(!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
        return cb(new Error('You can upload only image files!'), false);
    }
    cb(null, true);
};
const upload = multer({ storage: storage, fileFilter: imageFileFilter});
//const uploadImgFile = multer().single('imageFile');
const uploadRouter=express.Router();
uploadRouter.use(bodyParser.json());
uploadRouter.route('/')
.get(autheticate.verifyUser,autheticate.verifyAdmin,(req,res,next)=>{
    res.statusCode = 403;
    res.end('GET operation not supported on /imageUpload');
})
.post(autheticate.verifyUser,autheticate.verifyAdmin,upload.single('imageFile'),(req,res,next)=>{
   res.statusCode=200;
   res.setHeader('Content-Type','application/json');
   res.end('End');
})
.put(autheticate.verifyUser,autheticate.verifyAdmin,(req,res,next)=>{
    res.statusCode = 403;
    res.end('GET operation not supported on /imageUpload');
})
.delete(autheticate.verifyUser,autheticate.verifyAdmin,(req,res,next)=>{
    res.statusCode = 403;
    res.end('GET operation not supported on /imageUpload');
})
module.exports = uploadRouter;

I have set the body type of request message to form-data from POSTMAN,
But after changing body-format when I am uploading the image, the following error is given in POSTMAN

    <body>
        <h1>Unexpected token - in JSON at position 0</h1>
        <h2>400</h2>
        <pre>SyntaxError: Unexpected token # in JSON at position 0
    at JSON.parse (&lt;anonymous&gt;)
    at createStrictSyntaxError (F:\Cousera\Node\coursera-node-confusion-server\node_modules\body-parser\lib\types\json.js:157:10)
    at parse (F:\Cousera\Node\coursera-node-confusion-server\node_modules\body-parser\lib\types\json.js:83:15)
    at F:\Cousera\Node\coursera-node-confusion-server\node_modules\body-parser\lib\read.js:121:18
    at invokeCallback (F:\Cousera\Node\coursera-node-confusion-server\node_modules\raw-body\index.js:224:16)
    at done (F:\Cousera\Node\coursera-node-confusion-server\node_modules\raw-body\index.js:213:7)
    at IncomingMessage.onEnd (F:\Cousera\Node\coursera-node-confusion-server\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:1055:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)</pre>
    </body>
</html>

Two headers are contained in POSTMAN:
1. Content-Type: 'application/json'
2. Authentication: bearer [[TOKEN]]
Please I am unable to understand the error, I am very new to node.js. Please help me through it

like image 669
Asif Ahmed Avatar asked May 20 '18 08:05

Asif Ahmed


3 Answers

This issue occurs as you are passing Content-Type as application/json and uploading a file whose content-type is not json. Remove this header as it is not required.

like image 171
vinit_tiwari Avatar answered Nov 14 '22 15:11

vinit_tiwari


I had a similar problem, this is how i solved it.

Firstly from the client, do not specify content-type

then, when sending the request use this method

const file = new FormData();

if you are sending only the file

file.append('file', file, file.name);

if you are sending the file with something like a caption, then

file.append('file', file, file.name);
file.append('caption', fileCaption);

then make a post request to the server using the constant file

for example(using angular)

this.httpClient.post<Addpost>('localhost:3000/add/addFile', file)

in the server, you can catch the request by

router.post('/addFile', upload.single('file')
like image 38
ayotycoon Avatar answered Nov 14 '22 16:11

ayotycoon


I had the same error. The reason this happens is not because of setting the content-type. In fact, using multer you won't need to set the content-type in the header. The reason you get this error is because of what the response sends back. In this case, you're expecting JSON but it may have sent you back HTML. The error states:

Unexpected token - in JSON at position 0

Meaning, the response is probably not JSON. And why it's not JSON is because it may be HTML containing an error message caused by multer.

After changing the response type to text and seeing the error message, there was an error caused by the way I wrote the destination path to upload images to. And in your case, you need to turn it into a relative path, like so:

destination: (req, file, cb) => {
    cb(null, './uploads/images');
},

Also, be sure to create both uploads directory and images directory, so multer can find it.

like image 1
vazhin Avatar answered Nov 14 '22 15:11

vazhin