Reputation: 907
I am trying to get data from a SQL Server DB using node. I can make a connection and get data by running functions, but I would like to turn the functions into API endpoints.
Based on the error it seems to me that the res
variable isn't getting passed down into the last if statement, but I'm not seeing the issue.
I get a res.send is not a function
error when using a GET
method on this address from Postman.
let mssqlQuery = function(query, res) {
sql.connect(dbConfig, function(err) {
if (err) {
console.log("Error while connecting database :- " + err)
res.send(err)
} else {
let request = new sql.Request();
request.query(query, function(err, res) {
if (err) {
console.log("Error while querying database :- " + err)
res.send(err)
} else {
res.send(res) // res.send is not a function
}
})
}
})
}
// GET API
app.get("/api/address", function(req, res) {
var query = "select * from address"
mssqlQuery(query, res)
})
Is the res
variable improperly scoped or might I have the wrong approach entirely?
Upvotes: 0
Views: 1988
Reputation: 907
As @Sirko suggested, the res value was shadowed by an other variable. The corrected code:
let mssqlQuery = function(query, res) {
sql.connect(dbConfig, function(err) {
if (err) {
console.log("Error while connecting database :- " + err)
res.send(err)
} else {
let request = new sql.Request();
request.query(query, function(err, resp) { // Changed res to resp
if (err) {
console.log("Error while querying database :- " + err)
res.send(err)
} else {
res.send(resp) // res.send is not a function
}
})
}
})
}
Upvotes: 1