user6321478
user6321478

Reputation:

Node express app calling mssql is saying that Connection is closed

I have another app which uses express and routes but this new app i was slimming it down. I know the connection string stuff is correct

script.getQuestions(connection);

script.getQuestions = function(connection,req, res){
   console.log(connection);
}

I have read that some people said online to change to use a promise for async fixes this... problem is that with my function having req and res i don't know how to pass those in when i even try to refactor with a promise

"ConnectionError: Connection is closed"

"(module.js:487:32) code: 'ECONNCLOSED', name: 'ConnectionError' }"

What I call up (script) is

var sql = require('mssql');

exports.getQuestions = function(connection, req,res){
 console.log(connection);
var request = new sql.Request(connection);

var query = 'select * from Question'
request.query(query).then(function(resultset){
    res.json(resultset.recordset);
}).catch(function(err){
    console.log(err);
    //res.json(err)
})
}

Upvotes: 0

Views: 1882

Answers (1)

kWeglinski
kWeglinski

Reputation: 411

it's a bit hard to understand what you're doing there. But here is an promise example to use mssql

const sql = require('mssql')

sql.connect(config).then(pool => {
    // Query 

    return pool.request()
    .input('input_parameter', sql.Int, value)
    .query('select * from mytable where id = @input_parameter')
}).then(result => {
    console.dir(result)

    // Stored procedure 

    return pool.request()
    .input('input_parameter', sql.Int, value)
    .output('output_parameter', sql.VarChar(50))
    .execute('procedure_name')
}).then(result => {
    console.dir(result)
}).catch(err => {
    // ... error checks 
})

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

source: https://www.npmjs.com/package/mssql#promises

Upvotes: 1

Related Questions