Mitsuhiko Shimomura
Mitsuhiko Shimomura

Reputation: 259

request.on('row', function(columns) {}) never called

I connect to azure sql database by using NodeJS with Tedious. I succeed to connect, to INSERT and to SELECT. However, I cannot get columns' value when I insert a row to "user" table.

Code is here:

function insertUser(Name, res) {
    request = new Request("INSERT [user] (name, ticket) VALUES (@Name, @Ticket);", function(err) {
        if (err) {
            res.json({ Error: err });
        }
    });
    request.addParameter('Name', TYPES.NVarChar, Name);
    request.addParameter('Ticket', TYPES.Int,10);
    var result = {};
    request.on('row', function(columns) {
        columns.forEach(function(column) {
          if (column.value === null) {
            console.log('NULL');
          } else {
              result[column.metadata.colName] = column.value;
          }
        });
      res.json(result);
    }); 

    request.on('done', function(rowCount, more) {
        console.log(rowCount + ' rows returned');
    });
    connection.execSql(request);
}

And I call the function:

router.post('/register', function(req, res){
  console.log(req.body); // for logging
  if (req.body.name) {
    insertUser(req.body.name, res);
  }
});

Request from Terminal on Mac

curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"name":"XXXX"}'  http://localhost:3000/users/register

After that, the data was added, but res.json(result); was not called. I got this message: "curl: (52) Empty reply from server."

I want to get "user_id" of inserted user. Would you know any solutions?

Upvotes: 0

Views: 1637

Answers (1)

Mitsuhiko Shimomura
Mitsuhiko Shimomura

Reputation: 259

A solution of this problem is here: https://github.com/pekim/tedious/issues/117

Add select @@identity to the end of query. Like this:

'INSERT [user] (name, ticket) VALUES (@Name, @Ticket); select @@identity'

After that, I can get response data!

Upvotes: 2

Related Questions