nbroeking nbroeking - 5 months ago 98
Node.js Question

Unexpected token - while parsing json request

I have two node servers and I am trying to send files between them using a rest api. However when I am sending the data I get a "Unexpected token -"on the receiving server. On the sender I get an [Error: write after end].

My router code:

var express = require('express');
var multer = require('multer');
var path = require('path');

var Router = express.Router;

const MODULES_PACKAGES_UPLOAD_DIR = path.resolve('/tmp');

module.exports = function() {

var router = new Router();

var storage = multer.diskStorage({
destination: function(req, file, cb){
cb(null, MODULES_PACKAGES_UPLOAD_DIR);
}
});

var upload = multer({storage: storage});

router.post('/fileUpload', upload.array(), function(req, res){

debug('We have a a file');

//Send the ok response
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.end('\n');
}


The sending code:

var Util = require('util');
var http = require('request-promise');
var request = require('request');
var fs = require('fs');

var Post = require('http');
var FormData = require('form-data');

//Generate the form data
var formdata = modules.map(function(fileName){
return fs.createReadStream('/opt/files/'+fileName);
});

var data = getData(); //Gets the body of the code as a promise

return Promise.all(data)
.then(function(dataResults){

var options = {
method: 'POST',
uri: 'https://' + name +'/file',
rejectUnauthorized: false,
timeout: 2000,
body: {
keys: keyResults,
modules: modules,
},
formData: { <====== If I remove this section everything works
'module-package': formdata,
},
json: true // Automatically stringifies the body to JSON
};

request.post(options, function(err, response){
if( err){
debug('Error: ',err);
}
else{
debug('We posted');
}
});


The weird thing is that if I remove the formData section then everything works but when it is there I get an exception that says:

SyntaxError: Unexpected token -
at parse (/home/.../projects/node_modules/body-parser/lib/types/json.js:83:15)


Does anyone have any idea what I could be doing wrong??

Answer

Just in case anyone in the future comes with the same problem. As @Bergi mentioned. You cant have both json data and form data. You need to choose either one. The solution is to just pass the json data as apart of the form like.

var options = {
    method: 'POST',
    uri: 'https://' + name +'/file',
    rejectUnauthorized: false,
    timeout: 2000,
    body: {

    },
    formData: { 
      'module-package': formdata,
       keys: keyResults,
       modules: modules,
    },
    json: true // Automatically stringifies the body to JSON 
};

request.post(options, function(err, response){
    if( err){
      debug('Error: ',err);
    }
    else{
      debug('We posted');
    }
});