Node express error loading mysql driver
I am trying to use the code API to stop using express and mysql, but I have a problem inserting data into the 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 am using a simple firefox plugin for the restfull api and when I submit the Post {"task": "one"} method I get this error on the console: Error: ER_BAD_NULL_ERROR: The "Task" column cannot be null.
What am I doing wrong?
I think what's going on is that yours is req.body
n't getting filled, possibly due to a missing or misconfigured appropriate body processing middleware. The reason for this is that the module handles the javascript values and as the value of the mysql . Therefore, if not filled in, it means that the value of the mysql parameter will be used by the module . This throws the error you see because the task is not resolved for the column . mysql
undefined
null
null
req.body
req.body.task === undefined
null
mysql
null
Therefore, you need to make sure that:
-
You are using some kind of Json body parser, somewhere before this route. For example, body-parser contains a json parser that you can
use()
throughbodyParser.json()
. -
Your request is sent to the correct title
Content-Type
, such as:Content-Type: application/json
(optioncharset
can be added to the header valueContent-Type
).