'Trouble opening localhost with Node and mssql

I'm using Node to connect to a Microsoft SQL Developer database. I've finally gotten my code to run without errors:

var sql = require('mssql/msnodesqlv8');
const express = require('express');
const app = express();


// Get request
app.get('/', function (req, res) {


// Config your database credential
const config = {
    server: "xxxx",
    driver:"xxxx",
    database: "xxxx",
    user: "xxxx",
    password: "xxxx",
    options:{
    trustServerCertificate: true,
}
};

// Connect to your database
new sql.ConnectionError(config,function(err){

    // Create Request object to perform
    // query operation
    var request = new sql.Request();

    // Query to the database and get the records
    request.query('select * from mydb',
        function (err, records) {

            if (err) console.log(err)

            // Send records as a response
            // to browser
            res.send(records);

        });
    });
});


var server = app.listen(5000, function () {
    console.log('Server is listening at port 5000...');
});

But, when I go to :

http://localhost:5000/

It doesn't load, it says the page cannot be reached. What can I try to resolve this?



Solution 1:[1]

You're using the wrong thing to try and connect to SQL Server. You don't use new sql.ConnectionError(), you use sql.connect(). This error is causing your app to crash so nothing is listening on port 5000.

var sql = require('mssql/msnodesqlv8');
const express = require('express');
const app = express();


// Get request
app.get('/', function (req, res) {


// Config your database credential
const config = {
    server: "xxxx",
    driver:"xxxx",
    database: "xxxx",
    user: "xxxx",
    password: "xxxx",
    options:{
    trustServerCertificate: true,
}
};

// Connect to your database
sql.connect(config,function(err){

    // Create Request object to perform
    // query operation
    var request = new sql.Request();

    // Query to the database and get the records
    request.query('select * from mydb',
        function (err, records) {

            if (err) console.log(err)

            // Send records as a response
            // to browser
            res.send(records);

        });
    });
});


var server = app.listen(5000, function () {
    console.log('Server is listening at port 5000...');
});

Run that (after having applied proper database connection configuration values) and then you should be able to open your browser and connect to http://localhost:5000

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 squillman