I try to code rest API using express and mysql but i have problem with inserting data to database
router.route('/todo')
.post(function(req, res){
if(connection){
var obj = {
task: req.body.task,
date: Date()
}
connection.query('insert into task set ?', obj , function(err, info){
if (err) throw err;
console.log('dodano z id:' + info.insertId);
res.redirect('/');
});
}
})
.get(function(req, res){
if(connection) {
connection.query('select * from task order by id', function(err, rows){
if(err) throw err;
res.json(rows);
res.end;
});
}
});
I use a simple firefox plugin for restfull api and when i send Post method {"task":"one"} i get this error on console: Error: ER_BAD_NULL_ERROR: Column 'task' cannot be null.
What i do wrong?
I think what's happening is that your req.body is not being populated, perhaps due to a missing or misconfigured appropriate body handling middleware. The reasoning behind this is that the mysql module treats both javascript undefined and null values as the mysql null value. So if req.body is not being populated, that means req.body.task === undefined which means the mysql null value will be used by the mysql module. This causes the error you're seeing because null is not permitted for your task column.
So you need to make sure that:
You are using some sort of json body parsing middleware somewhere before that route. So for example body-parser has a json body parser that you can use() via bodyParser.json().
Your request is sending the proper Content-Type header, for example: Content-Type: application/json (a charset parameter can optionally be added to the Content-Type header value).