SQL Server How do I connect to my sql instance with node.js

ubbxdtey  于 2023-11-16  发布在  Node.js
关注(0)|答案(2)|浏览(90)

As the title says, I am trying to connect to my MSSQL instance using node.js. I have used many different versions of the code I have found on stack exchange, reddit, and tutorials from other sites. Nothing has seemed to work though. Whenever I use the wrong server I get a different error, but when I use this server I get an ETIMEOUT error.

The specific error is: Database connection failed: ConnectionError: Failed to connect to localhost\SQLEXPRESS in 15000ms

This is some of the code I have tried. Every time I get the same error. I have been able to connect to the server and access the database using SSMS.

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

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

const config = {
  user: "tester",
  password: "test",
  server: "localhost\\SQLEXPRESS",
  database: "TrainingSimulator",
};

/******************************************************************/
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}]`);
});

I have also used:

const express = require('express');
const mssql = require('mssql');
const cors = require('cors');

const app = express();
const port = 3000; // or any port you prefer

app.use(cors());
app.use(express.json());

// Database configuration
const dbConfig = {
  server: 'localhost\\SQLEXPRESS',
  database: 'TrainingSimulator',
  user: 'tester',
  password: 'test',
};

// Connect to the database
mssql.connect(dbConfig, (err) => {
  if (err) {
    console.error('Database connection failed:', err);
  } else {
    console.log('Connected to the database');
  }
});

// Define API endpoints to interact with the database

// Start your server
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
wtlkbnrh

wtlkbnrh1#

I had to go to SQL Server Configuration Manager, and from there enable the tcp/ip service. I also had to go to my windows services manager and changed sql server browser and sql server agent from disabled to enabled

yhuiod9q

yhuiod9q2#

You can try using mysql2 package instead of mysql there are some Authorization constraints in mysql package I was facing the same issue. I fixed it by using mysql2 instead of mysql. commands you can use npm uninstall mysql and npm i mysql2 and then import it.

相关问题