Home > Mobile >  ER_BAD_NULL_ERROR when inserting value into column with nodejs mysql
ER_BAD_NULL_ERROR when inserting value into column with nodejs mysql

Time:12-26

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

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;

CodePudding user response:

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.

  • Related