Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ER_BAD_NULL_ERROR when inserting value into column with nodejs + mysql

I am trying to insert a value using postman to test my api. My class table have 2 columns (classId which is auto incremented and classes). However, I kept getting this error message and I am unsure of how to solve this.

This is the postman result.
Postman result

This is my database table class.
MySQL class table

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is my code.

const db = require('../config/databaseConfig');
const adminDB = {};

adminDB.createClass = (classes, callback) => {
    var dbConn = db.getConnection();

    dbConn.connect(function (err) {
        if (err) {
            return callback(err, null); 
        }

        const query = "INSERT INTO practiceme.class (classes) VALUES (?)";
        dbConn.query(query, [classes], (err, results) => {  
            dbConn.end();
            if (err) {
                console.log(err);
                return callback(err, null);
            } else {
                return callback(null, results);
            }
        });
    });
};
module.exports = adminDB;
const express = require("express");
const router = express.Router();
const adminDB = require("../model/admin");

router.post("/createClass", (req, res, next) => {
    var {classes} = req.body;

    adminDB.createClass(classes,(err, results) => {
        if (err) {
          return res.status(500).send({ err });
        }

        return res.status(200).json(results);
      }
    );
  }
);

module.exports = router;

>Solution :

You’re sending the classes variable as a query parameter. To access it from req, you should use req.query instead of req.body.

Change from:

var {classes} = req.body;

to:

var {classes} = req.query;

Or, in Postman, you select the Body tab and then type the body of the request in JSON format. Then your actual code should work.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading