Arnab Das Joy
Arnab Das Joy

Reputation: 21

Tell me a fix for ER_BAD_NULL_ERROR in Node.js, mysql crud operation

I am an absolute novice at Node.js. So, as I'm learning, I ran into this problem. I am adding codes from backend for CRUD (This index.js may seem incomplete, because I faced the problem halfway and then started seeking the solution.)

package.json

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "mysql": "^2.18.1",
    "nodemon": "^2.0.20"
  }
}

index.js

import express from 'express';
import mysql from "mysql";

const app = express();

const db = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "akdkfjdkfj;a",
    database: "online_sustainability_db"
});

app.use(express.json());   

app.get("/", (req, res) =>{
    res.json("Hello. You are connected to backend.");
});

app.get("/data", (req, res) =>{
    const query = "SELECT * FROM online_sustainability_db.idea_proposers";
    db.query(query, (err, data)=>{
        if(err)
            return res.json(err);
        else 
            return res.json(data);
    })
});

app.post("/data", (req, res)=>{
    const q = "INSERT INTO idea_proposers (`last_name`, `first_name`, `account_no`, `github_repository_link`, `submission_id`) VALUES (?, ?, ?, ?, ?)";
    
    const last_name = req.body.last_name;
    const first_name = req.body.first_name; 
    const account_no = req.body.account_no; 
    const github_link = req.body.github_repository_link; 
    const submission_id = req.body.submission_id;
    
    
    db.query(q, [last_name, first_name, account_no, github_link, submission_id], (err, data)=>{
        if(err)
            return res.json(err);
        else 
            return res.json("Provided data were recorded successfully.");
    });
});

app.listen(8800, ()=>{
    console.log("Connected to backend!");
});

The following image is from postman application. This is the error I am getting. Please, help me fixing it. enter image description here

This is the description of the table I am trying to post the data in. enter image description here

I tried doing some syntactical change and running the code several times. Well, it didn't work. I even looked for resources online, but I couldn't find any similar.

Upvotes: 0

Views: 118

Answers (1)

Mostafa Fakhraei
Mostafa Fakhraei

Reputation: 3687

Kindly select the JSON from Postman whenever you want to send the JSON data. currently, you're sending data as a text.

Upvotes: 1

Related Questions