NodeJS backend post request posts data to the SQL Server table as 'NULL' values

Viewed 51

I'm trying to POST data to a SQL Server table from my NodeJS backend with the help of the mssql package. I had multiple errors coming up before but after reading, watching tutorials and with some help I was able to get the code to a point with no erros.

But now the issue I have is once I try to post some data using Postman, I get an HTTP 201 Created successful status but I only see a set of 'NULL' values in the table.

PS: I got all my GET routes working great

This is the code :

api.js:

var Db = require('./dboperations');
var Ctms = require('./ctms')
var dboperations = require('./dboperations');

var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
var router = express.Router();

app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.use(cors());
app.use('/api', router);

router.use((request,response,next)=> {
    console.log('middleware');
    next();
})

router.route('/ctms').get((request,response)=>{
    dboperations.getCtms().then(result => {
        response.json(result[0]);
    })
})

router.route('/ctms/:id').get((request,response)=>{
    dboperations.getCtmsID(request.params.id).then(result => {
        response.json(result[0]);
    })
})

router.route('/ctms/normacs/all').get((request,response)=>{
    dboperations.getallshopOrders().then(result => {
        response.json(result[0]);
    })
})

router.route('/ctms/normacs/machine/:ID').get((request,response)=>{
    dboperations.getshopOrders(request.params.ID).then(result => {
        response.json(result[0]);
    })
})

router.route('/ctms/normacs/runningSO/:machine').get((request,response)=>{
    dboperations.getrunningshopOrders(request.params.machine).then(result => {
        response.json(result[0]);
    })
})

router.route('/ctms/employees/loggedin').get((request,response)=>{
    dboperations.getloggedEmployees().then(result => {
        response.json(result[0]);
    })
})

router.route('/ctms').post((request, response) => {
    let ctms = { ...request.body }
    Db.addCtms(ctms).then(result  => {
    response.status(201).json(result);
    })
})

var port = process.env.PORT || 8090;
app.listen(port);
console.log('CTMS API is running at ' + port);

dboperations.getCtms().then(result => {
    console.log(result);
})

dboperations.getshopOrders().then(result => {
    console.log(result);
})

dboperations.getallshopOrders().then(result => {
    console.log(result);
})

dboperations.getloggedEmployees().then(result => {
    console.log(result);
})

ctms.js

class  Ctms {
    constructor(UNIQUE_ID,shop_order,item_number,item_desc,machine,supplier,feet_coil,Date_on,load_no,loadpc_signoff,pc_staff_load,unloadpc_signoff,pc_staff_unload,Date_off,ctms_id,complete){
      this.UNIQUE_ID = UNIQUE_ID;
      this.shop_order = shop_order;
      this.item_number = item_number;
      this.item_desc = item_desc;
      this.machine = machine;
      this.supplier = supplier;
      this.feet_coil = feet_coil;
      this.Date_on = Date_on;
      this.load_no = load_no;
      this.loadpc_signoff = loadpc_signoff;
      this.pc_staff_load = pc_staff_load;
      this.unloadpc_signoff = unloadpc_signoff;
      this.pc_staff_unload = pc_staff_unload;
      this.Date_off = Date_off;
      this.ctms_id = ctms_id;
      this.complete = complete;
    }
  }
  
  module.exports = Ctms;

dboperations.js:

var config = require('./dbconfig');
const sql = require('mssql');

async function getCtms(){
    try{
        let pool = await sql.connect(config);
        let ctms = await pool.request()
            .query("SELECT * FROM ctms");
        return ctms.recordsets;
    }
    catch (error){
        console.log(error);
    }
}

async function getCtmsID(ctmsID){
    try{
        let pool = await sql.connect(config);
        let ctms = await pool.request()
            .input('input_parameter', sql.Int, ctmsID)
            .query("SELECT * FROM ctms where ID = @input_parameter");
        return ctms.recordsets;
    }
    catch (error){
        console.log(error);
    }
}

async function getallshopOrders(){
    try{
        let pool = await sql.connect(config);
        let ctms = await pool.request()
            .query("SELECT distinct(sf.ord_no), sf.ID ,sf.item_no,sf.item_desc_1, sd.wc FROM REF_SFORDFIL_SQL sf INNER JOIN REF_sfdtlfil_sql sd ON sf.ord_no = sd.ord_no where (sd.wc = 'NOR1' OR sd.wc = 'NOR2' OR sd.wc = 'NOR3' OR sd.wc = 'NOR4' OR sd.wc = 'NOR5' OR sd.wc = 'NOR6' ) and ord_status = 'R' order by sd.wc asc,sf.ord_no");
        return ctms.recordsets;
    }
    catch (error){
        console.log(error);
    }
}

async function getshopOrders(normacNo){
    try{
        let pool = await sql.connect(config);
        let ctms = await pool.request()
            .input('input_parameter', sql.NChar, normacNo)
            .query("SELECT distinct(sf.ord_no), sf.ID, sf.item_no,sf.item_desc_1 FROM REF_SFORDFIL_SQL sf INNER JOIN REF_sfdtlfil_sql sd ON sf.ord_no = sd.ord_no where sd.wc = @input_parameter and ord_status = 'R' order by sf.ord_no");
        return ctms.recordsets;
    }
    catch (error){
        console.log(error);
    }
}

async function getrunningshopOrders(machine){
    try{
        let pool = await sql.connect(config);
        let ctms = await pool.request()
            .input('input_parameter', sql.NChar, machine)
            .query("SELECT * FROM ACT_CURRENT_SO where machine = @input_parameter");
        return ctms.recordsets;
    }
    catch (error){
        console.log(error);
    }
}

async function getloggedEmployees(){
    try{
        let pool = await sql.connect(config);
        let ctms = await pool.request()
            .query("SELECT * FROM ACT_LOGGED_EMP");
        return ctms.recordsets;
    }
    catch (error){
        console.log(error);
    }
}

async function addCtms(ctms) {
    try {
      let pool = await sql.connect(config);
      let insertCtms = await pool.request()
      .input('shop_order', sql.NChar(20), ctms.shop_order)
      .input('item_number', sql.NChar(20), ctms.item_number)
      .input('item_desc', sql.NChar(50), ctms.item_desc)
      .input('machine', sql.NChar(10), ctms.machine)
      .input('supplier', sql.NChar(20), ctms.supplier)
      .input('feet_coil', sql.NChar(10), ctms.feet_coil)
      .input('Date_on', sql.NChar(10), ctms.Date_on)
      .input('load_no', sql.NChar(15), ctms.load_no)
      .input('loadpc_signoff', sql.NChar(10), ctms.loadpc_signoff)
      .input('pc_staff_load', sql.NChar(10), ctms.pc_staff_load)
      .input('unloadpc_signoff', sql.NChar(10), ctms.unloadpc_signoff)
      .input('pc_staff_unload', sql.NChar(15), ctms.pc_staff_unload)
      .input('Date_off', sql.NChar(10), ctms.Date_off)
      .input('ctms_id', sql.NChar(15), ctms.ctms_id)
      .input('complete', sql.NChar(10), ctms.complete)
      .query("INSERT INTO ctms (shop_order, item_number, item_desc, machine, supplier, feet_coil, Date_on, load_no, loadpc_signoff, pc_staff_load, unloadpc_signoff, pc_staff_unload, Date_off, ctms_id, complete) values (@shop_order, @item_number, @item_desc, @machine, @supplier, @feet_coil, @Date_on, @load_no, @loadpc_signoff, @pc_staff_load, @unloadpc_signoff, @pc_staff_unload, @Date_off, @ctms_id, @complete)")
      return  insertCtms.recordsets;
    }
    catch (err) {
      console.log(err);
    }
  }

module.exports = {
    getCtms : getCtms,
    getshopOrders : getshopOrders,
    getallshopOrders : getallshopOrders,
    getCtmsID : getCtmsID,
    getrunningshopOrders : getrunningshopOrders,
    getloggedEmployees : getloggedEmployees,
    addCtms : addCtms
}

dbconfig.js:

const config = {
    user : 'XXXXX',
    password : 'XXXXX',
    server : 'XXXXX',
    database : 'XXXXX',
    options : {
        trustedConnection: true,
        encrypt: true,
        enableArithAbort: true,
        trustServerCertificate: true
    },
    port : 1433
}

module.exports = config;

Those are the JS files I have inside my server folder. I have a separate client for the ReactJS front-end to do CRUD operations with the SQL Server database.

This is the query for the ctms table in SQL Server:

CREATE TABLE [dbo].[ctms]
(
    [UNIQUE_ID] [int] IDENTITY(1,1) NOT NULL,
    [shop_order] [nchar](20) NULL,
    [item_number] [nchar](20) NULL,
    [item_desc] [nchar](50) NULL,
    [machine] [nchar](10) NULL,
    [supplier] [nchar](20) NULL,
    [feet_coil] [nchar](10) NULL,
    [Date_on] [nchar](10) NULL,
    [load_no] [nchar](15) NULL,
    [loadpc_signoff] [nchar](10) NULL,
    [pc_staff_load] [nchar](10) NULL,
    [unloadpc_signoff] [nchar](10) NULL,
    [pc_staff_unload] [nchar](15) NULL,
    [Date_off] [nchar](10) NULL,
    [ctms_id] [nchar](15) NULL,
    [complete] [nchar](10) NULL,

    CONSTRAINT [PK_ctms] 
        PRIMARY KEY CLUSTERED ([UNIQUE_ID] ASC)
                    WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
                          IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
                          ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

Finally this is the outcome I get after try to post data from Postmanto the routehttp://localhost:8090/api/ctms`.

Here in the ctms table figure, first 4 records are the outcome I want to see(manually inserted for the demonstration purposes) and from 5 to 9 are the currently what happens when I post data via Postman.

Postman

ctms table in SQL Server database

1 Answers

All this time the issues was not in my code, actually it was the way I tried to post data using an object inside an array. All I did was removing the array brackets in Postman and there you go, the data is showing in the SQL Server table.

Related