Issue
I'm actually developping an Angular webform with a file upload and some data. Here are the request headers:
POST /tests/add HTTP/1.1
Host: localhost:3000
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate
Content-Type: application/json;charset=utf-8
Referer: http://localhost:8000/
Content-Length: 2033
I build the request this way:
var formData = new FormData();
formData.append('file', $scope.test.file);
$http({
method: 'POST',
url: backUrl + '/tests/add',
data: { 'file': $scope.file,
'token': 'test'},
contentType: false,
processData: false,
transformRequest: function (data, headersGetter) {
var formData = new FormData();
angular.forEach(data, function (value, key) {
formData.append(key, value);
});
var headers = headersGetter();
delete headers['Content-Type'];
return formData;
}
But it always return a 400 bad request with this error:
Unexpected token -
400
SyntaxError: Unexpected token -
at parse (/home/me/projects/www/node_modules/body-parser/lib/types/json.js:83:15)
at /home/me/projects/www/node_modules/body-parser/lib/read.js:116:18
at invokeCallback (/home/me/projects/www/node_modules/raw-body/index.js:262:16)
at done (/home/me/projects/www/node_modules/raw-body/index.js:251:7)
at IncomingMessage.onEnd (/home/me/projects/www/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)
This is the only reference to bodyParser I have in my backend:
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true,
defer: true
}));
What am I doing wrong ?
Solution
Are you positive you're sending JSON?
Most likely you are using invalid JSON which forces error with bodyParser.json().
Make sure you are using valid JSON. You can also swap bodyParser.json with bodyParser.raw for middleware.
Answered By - defaultcheckbox
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.