DEV Community

KISHAN RAMLAKHAN NISHAD
KISHAN RAMLAKHAN NISHAD

Posted on

Creating a Server and Connecting to MSSQL

// Import required modules
const express = require('express');
const sql = require('mssql');

// Initialize Express app
const app = express();

// Middleware for parsing JSON
app.use(express.json());

// MSSQL Database Configuration
const dbConfig = {
  user: 'your_username',
  password: 'your_password',
  server: 'localhost', // or your server name
  database: 'your_database',
  options: {
    encrypt: false, // Use true for Azure
    trustServerCertificate: true, // Use true if you're using a self-signed certificate
  },
};

// Connect to MSSQL
sql.connect(dbConfig)
  .then((pool) => {
    if (pool.connected) {
      console.log('Connected to MSSQL database');
    }
  })
  .catch((err) => {
    console.error('Error connecting to MSSQL database:', err);
  });

// Basic Route
app.get('/', (req, res) => {
  res.send('Server is running and connected to MSSQL');
});

// Start the server
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Enter fullscreen mode Exit fullscreen mode

Top comments (0)