1

I am getting the following error while sending the request from Postman and I am using Node.js for backend.

Error:

POST /api/users/save-card-details 400 31.719 ms - 871
SyntaxError: Unexpected token -
    at parse (/opt/lampp/htdocs/heroku/FGDP/node_modules/body-parser/lib/types/json.js:83:15)
    at /opt/lampp/htdocs/heroku/FGDP/node_modules/body-parser/lib/read.js:116:18
    at invokeCallback (/opt/lampp/htdocs/heroku/FGDP/node_modules/raw-body/index.js:262:16)
    at done (/opt/lampp/htdocs/heroku/FGDP/node_modules/raw-body/index.js:251:7)
    at IncomingMessage.onEnd (/opt/lampp/htdocs/heroku/FGDP/node_modules/raw-body/index.js:307:7)
    at emitNone (events.js:86:13)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)

My code is below:

server.js:

 var express=require('express');
    var morgan = require('morgan');
    var http=require('http');
    var bodyParser= require('body-parser');
    var methodOverride = require('method-override');
    var mongo = require('mongojs');
    var session = require('express-session');
    var app=module.exports=express();
    var server=http.Server(app);
    var port=8989;
    var admin=require('./route/route.js');
    var api=require('./api/api.js');
    app.use(express.static(__dirname + '/public'));     // set the static files location /public/img will be /img for users
    app.use(morgan('dev'));                     // log every request to the console
    app.use(bodyParser.urlencoded({ extended: false,limit: '5mb' }))    // parse application/x-www-form-urlencoded
    app.use(bodyParser.json({limit: '5mb'}))    // parse application/json
    app.use(methodOverride());                  // simulate DELETE and PUT
    app.use(session({secret: 'FGDPlexel',resave: true,saveUninitialized: true}));
    app.get('/',function(req,res){
        res.sendFile(__dirname + '/index.html');
    })
app.post('/api/users/save-card-details',api.saveCardDetails);

api.js:

var multer  = require('multer');
var storage =multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './../uploads');
  },
  filename: function (req, file, callback) {
    callback(null, Date.now()+'-'+file.originalname);
  }
});
var upload = multer({ storage: storage });
exports.saveCardDetails=function(upload.single('image'),req,res){
    var name=req.body.name;
    var company=req.body.company;
    var position=req.body.position;
    var mobile=req.body.mobile;
    var email=req.body.email;
    var landline=req.body.landline;
    var url=req.body.url;
    var postcode=req.body.postcode;
    var address=req.body.address;
    var image=req.body.image;
    var userid=req.body.userid;
    var profiletext=req.body.profile;
    var biography=req.body.biography;
    var token_id=req.body.token_id;
    console.log('request',req);
}

Here I am sending request using postman and set header Content-Type:application/json . The screen shot is given below.

enter image description here

Here I need to upload the image first and then get the image name along with all other data but getting the above error.

halfer
  • 19,824
  • 17
  • 99
  • 186
satya
  • 3,508
  • 11
  • 50
  • 130
  • I think the problem is that you are not sending a valid JSON. I would put some print in json.js to print what it actually receives. – LEQADA Aug 19 '17 at 09:51
  • I am sending via postman and set also header `Content-Type:application/json` and its `form-data`. – satya Aug 19 '17 at 09:52
  • But if you will look to the json.js code you will see that the error you get occurs when the request body is not a valid JSON. – LEQADA Aug 19 '17 at 09:55
  • I checked and got this `if (first !== '{' && first !== '[') { debug('strict violation') throw new SyntaxError('Unexpected token ' + first) }` line. BUt i am using third party tool. Can you please share the solutions. – satya Aug 19 '17 at 09:57
  • If you on postman click in bulk edit, on the top right part off you jason response, its will let you edit like it was a normal JSON format. May its can turn easier to find the solution – Yago Azedias Aug 19 '17 at 10:02
  • @YagoAzedias : I did as per you and got `name:subhrajyoti company:oditek solutions position:soft mobile:9937229853 email:s@gmail.com landline:231293 url:http://abcd.org postcode:123456 address:Rasulgarh userid:1234 profile:wesd biography:wsde token_id:1234567890` but where is my image data ? – satya Aug 19 '17 at 10:07

1 Answers1

0

I don't know why, but looks like request doesn't contain a valid JSON.

If you will go to the

/opt/lampp/htdocs/heroku/FGDP/node_modules/body-parser/lib/types/json.js:83:15)

You will see this function

function parse(body) {
  if (body.length === 0) {
    return {}
  }

  if (strict) {
    var first = firstchar(body)

    if (first !== '{' && first !== '[') {
      debug('strict violation')
      throw new SyntaxError('Unexpected token ' + first) <--- Your error
    }
  }

  debug('parse json')
  return JSON.parse(body, reviver)
}

The nice thing about node.js is you can easily change the code of libraries on fly. So I would make a console.log of body and see what is actually going on.

LEQADA
  • 1,913
  • 3
  • 22
  • 41
  • I did as per you and in console I got many binary data along with `------WebKitFormBoundaryLwByidAXLCzb02qO Content-Disposition: form-data; name="userid" 1234 ------WebKitFormBoundaryLwByidAXLCzb02qO Content-Disposition: form-data; name="profile" wesd ------WebKitFormBoundaryLwByidAXLCzb02qO Content-Disposition: form-data; name="biography" wsde ------WebKitFormBoundaryLwByidAXLCzb02qO Content-Disposition: form-data; name="token_id" 1234567890 ` – satya Aug 19 '17 at 10:05
  • Exactly. So it is not a JSON at all. Maybe try another tool to send a request. Like curl. This answer may help you [How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?](https://stackoverflow.com/a/7173011/980828) – LEQADA Aug 19 '17 at 10:10
  • So you got it. Maybe you are just trying to manipulate a binary format like was other normal object – Yago Azedias Aug 19 '17 at 10:11
  • Has curl to send image also ? – satya Aug 19 '17 at 10:11
  • You can't send an image as "image" in JSON :). Maybe it will be better if you will encode it to Base64 and try to send it as a string – LEQADA Aug 19 '17 at 10:13
  • Host your image and send the url – Yago Azedias Aug 19 '17 at 10:16
  • Actually I am testing the REST API and using the tool like `postman` . It has also the image upload format so it should take. – satya Aug 19 '17 at 10:16
  • Actually I have one image to upload with other data . If image will be not there then it is very easy to get all other data using `x-www-form-urlencoded`. Can anybody suggest me what to do while testing APIS. – satya Aug 19 '17 at 10:26
  • @satya [Posting a File and Associated Data to a RESTful WebService preferably as JSON](https://stackoverflow.com/a/4083908/980828) – LEQADA Aug 19 '17 at 10:41