1

I'm new in nodejs I just want to connect my nodjs app to Microsoft SQL server 2014 anyone help me to know what is wrong in my code, please this is my code below

const sql = require("mssql");

 /*-------------------add details of sqlConfig-----------------*/

const config ={
user: 'sa',
password: '*******',
server: 'localhost',
database: 'test'
};
/******************************************************************/ 
app.get('/', function(req, res){
let connection = sql.connect(sqlConfig,err => {

if(err){
  console.log(err);
}
else{
 res.send('DB Connected');
 //code for sql request here
 const request = new sql.Request();
 app.listen(port,function(){
 console.log('Server started at ${PORT}');
 // SQL Query here
 request.query('select * from Tb...').then(res=>{
 console.log(res);  });

});}
})
})
4
  • 1
    do you setup port variable? Commented Nov 25, 2021 at 17:16
  • 2
    Do you get some sort of error? Do you have a default instance of SQL Server installed on the box where this code is running? Commented Nov 25, 2021 at 17:38
  • @AlexYu , Yes Mr.Alex , here is the code of setup: const PORT = process.env.PORT || 5000; app.listen(PORT, () => { console.log(Server is running on PORT: ${PORT}); }); Commented Nov 25, 2021 at 18:46
  • @DavidBrowne-Microsoft the connection failed , sure I have installed the SQL server properly Commented Nov 25, 2021 at 18:48

1 Answer 1

3

First:

I am guessing that you are trying this on your local machine and that you are using the self signed cert from mssql ? If so make sure to set the option trustServerCertificate: true in the config object.

Second:

The sql.connect function is a Promise which you have either to await or to use the .then .catch syntax.

Here a very basic example with await syntax:

const express = require('express');
const sql = require("mssql");
const app = express();

/*-------------------add details of sqlConfig-----------------*/

const config = {
  user: "sa",
  password: "duvoia1-rfas+dfc",
  server: "localhost",
  database: "master",
  options: {
    trustServerCertificate: true
  }
};

/******************************************************************/
app.get("/", async (req, res) => {
    try {
        await sql.connect(config);
        res.send("DB Connected");
    } catch(err)
    {
        res.send(err);
    }
});

const port = process.env.PORT || 5000;
app.listen(port, () => {
  console.log(`service is running on:: [${port}]`);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.