0

There is an Angular 4 client side Nodejs-Express back end and PostgreSQL database. The problem is that if I want to send data to server ( in my submodule, what is a todo function ) the backend send me the next:

My error message is:

POST /api/datatodo 500 1.150 ms - 969 error: invalid input syntax for integer: ""

modal.ts

class Searches {
    _id: string;
    title: string;
    newdata: string;


    constructor(
    ){
        this.title = ""
        this._id = ""
        this.newdata = ""
    }
}

the insert query on backend:

function createSearch(req, res, next) {
  req.body.launched = parseInt(req.body.launched);
  db.none('INSERT INTO table (userid, word)' +
      'values(${_id}, ${newdata})',
    req.body)
    .then(function () {
      res.status(200)
        .json({
          status: 'success',
          message: 'Cool'
        });
    })
    .catch(function (err) {
      return next(err);
    });
}
vitaly-t
  • 24,279
  • 15
  • 116
  • 138
  • You must transform `''` to `NULL`; PostgreSQL doesn't accept the empty string as a valid representation of a null integer. – Craig Ringer Nov 13 '17 at 12:50

1 Answers1

1

pg-promise formats values according to their JavaScript type. And from the error it looks like at least one of _id or newdata is a string, while an integer is expected.

So what you did for field launched, which you do not even use, you should do to those fields to rectify the type:

const a = req.body;
a._id = +a._id;
a.newdata = +a.newdata;
db.none('INSERT INTO table(userid, word) VALUES(${_id}, ${newdata})', a)

That's the recommended approach. Alternatively, you can do server-side casting by appending ::int to the integer parameters:

db.none('INSERT INTO table(userid, word) VALUES(${_id}::int, ${newdata}::int)', req.body)

And another usable approach:

const a = req.body;
db.none('INSERT INTO table(userid, word) VALUES($1, $2)', [+a._id, +a.newdata])
vitaly-t
  • 24,279
  • 15
  • 116
  • 138