Search code examples
javascriptnode.jsnode-mssql

Can't get Node mssql to work properly


This is the way I'm using mssql at the moment but it gives sometimes errors:

JavaScript:

router.get('/academiejaren', (req, res) => {
    sql.connect(dbconfig, function (err) {
        var request = new sql.Request();
        if (err) {
            console.log(err);
            return;
        }
        request.query("SELECT * FROM [Alg].[DefAJ];", function (err, recordset) {
            if (err) {
                console.log(err);
                return;
            }
            else {
                res.end(JSON.stringify(recordset));
            }
        });
        request.query();
    });
});

Error:

{ ConnectionError: Connection is closed.
    at C:\Users\Milan\Documents\Octopus\Octopus 2.0\node_modules\mssql\lib\main.js:1569:17
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
  name: 'ConnectionError',
  message: 'Connection is closed.',
  code: 'ECONNCLOSED' }
(node:556) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ConnectionError: Connection is closed.
(node:556) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I'm using version 3.2.0 because I can't get the newest one, 4.0.2, to work... Any help or some good examples, because I can't figure out the documentation...

thank in advance!

EDIT

Updated on a small test project to 4.0.2. and I got it to work. Going to change my API to this update.

router.get('/academiejaren', (req, res) => {
    (async function () {
        try {
            let pool = await sql.connect(config)
            let result1 = await pool.request()
                .query('SELECT * FROM [Alg].[DefAJ];')

            res.send(JSON.stringify(result1.recordset));


        } catch (err) {
            res.send("CAUGHT ERROR academiejaren");
        }
    })()

    sql.on('error', err => {
        // ... error handler
    })
});

Now I do have a small question left, what should I do with the catch and sql.on()? How should I handle error's?


Solution

  • router.get('/academiejaren', (req, res) => {
        sql.connect(dbconfig, function (err) {
            var request = new sql.Request();
            if (err) {
                console.log(err);
                return;
            }
            request.query("SELECT * FROM [Alg].[DefAJ];", function (err, recordset) {
                if (err) {
                    console.log(err);
                    return;
                }
                else {
                    res.send(JSON.stringify(recordset));
                }
            });
            request.query();
        });
    });
    

    you literally did res.end, end exits it, you want res.send