I have been immersing myself in learning the MEAN stack and am currently engrossed in building a simple Todo application.
However, I keep encountering this JSON error:
POST /api/todos 400 20.659 ms - 612
Error: invalid json
at parse (/Users/Angular_To_Do/node_modules/body-parser/lib/types/json.js:60:15)
at /Users/Angular_To_Do/node_modules/body-parser/lib/read.js:96:18
at IncomingMessage.onEnd (/Users/Angular_To_Do/node_modules/body-parser/node_modules/raw-body/index.js:136:7)
at IncomingMessage.g (events.js:199:16)
at IncomingMessage.emit (events.js:129:20)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)
As a beginner, I have thoroughly checked my code for errors, but I cannot seem to pinpoint what is causing this issue. I have set up app.use(bodyParser.json()) to send a JSON object, yet it still does not work. Please enlighten me on why this might be happening…
//Server.js
app.use(express.static(__dirname + '/public'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride('X-HTTP-Method-Override'));
var Todo = mongoose.model('Todo', {
text : String
});
app.get('/api/todos', function(req, res){
Todo.find(function(err, todos){
if(err){
res.send(err)
}
res.json(todos)
});
});
app.post('/api/todos', function(req, res){
Todo.create({
text: req.body.text,
done: false
}, function(err, todo){
if(err){
res.send(err);
}
Todo.find(function(err,todos){
if(err){
res.send(err)
}
res.json(todos);
});
});
});
Here is the Controller file:
var myTodo = angular.module('myTodo',[ ])
myTodo.controller('taskController',function($scope, $http){
$http.get('/api/todos')
.success(function(data){
$scope.todos = data;
console.log(data);
})
.error(function(data){
console.log('Error: ' + data);
});
$scope.addListItem = function(){
$http.post('/api/todos', $scope.formData)
.success(function(data){
$scope.formData = "";
$scope.todos = data;
console.log(data);
})
.error(function(data){
console.log('Error: ' + data);
});
};
Please see the HTML snippet here:
<div ng-controller = "taskController">
<form>
<input type="text" class="" placeholder="" ng-model="formData">
<button style = "margin-top:50px"
type = "submit"
ng-click = "addListItem()">
ADD SOME TASKS
</button>
</form>
</div>
I am using Express 4.7 and Angular 1.3.15. Despite my efforts, I am unable to progress beyond this error. Your guidance would be greatly appreciated. Thank you.