Getting an error when resending the get request

When i send the request first time it works fine but when i send the request second time it says " Error fetching project: TypeError: The "config.server" property is required and must be of type string."
my-project/
├── config/
│ └── db.js
├── controllers/
│ ├── propertyController.js
│ └── projectController.js
├── models/
│ ├── propertyModel.js
│ └── projectModel.js
├── routes/
│ ├── propertyRoutes.js
│ └── projectRoutes.js
├── server.js
├── .env
└── package.json

my-project/
├── config/
│ └── db.js
├── controllers/
│ ├── propertyController.js
│ └── projectController.js
├── models/
│ ├── propertyModel.js
│ └── projectModel.js
├── routes/
│ ├── propertyRoutes.js
│ └── projectRoutes.js
├── server.js
├── .env
└── package.json

ERROR ..
npm start

> node server.js

Server running on port 5000
Connected to SQL Server
Error fetching project: TypeError: The "config.server" property is required and must be of type string.
npm start

> node server.js

Server running on port 5000
Connected to SQL Server
Error fetching project: TypeError: The "config.server" property is required and must be of type string.
19 Replies
Faisu0p
Faisu0pOP3mo ago
in what file can the issue be in ? when i sent the request first itme , it wokrs like a charm , but when i sends it again it gives this error and when i restart the server it woks fine 1 time and again error 2nd time
Faisu0p
Faisu0pOP3mo ago
First time
No description
Faisu0p
Faisu0pOP3mo ago
2nd time
No description
vinter.
vinter.3mo ago
I assume it's something in db.js and how you're instancing the connection object
Faisu0p
Faisu0pOP3mo ago
// config/db.js
const sql = require('mssql');
require('dotenv').config();

// Database configuration
const config = {
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
server: process.env.DB_SERVER,
database: process.env.DB_NAME,
options: {
encrypt: true, // For Azure SQL, set to true
trustServerCertificate: true
}
};

// Function to connect to the database
const connectDB = async () => {
try {
await sql.connect(config);
console.log('Connected to SQL Server');
} catch (err) {
console.error('Error connecting to SQL Server:', err);
}
};

module.exports = { connectDB, sql };
// config/db.js
const sql = require('mssql');
require('dotenv').config();

// Database configuration
const config = {
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
server: process.env.DB_SERVER,
database: process.env.DB_NAME,
options: {
encrypt: true, // For Azure SQL, set to true
trustServerCertificate: true
}
};

// Function to connect to the database
const connectDB = async () => {
try {
await sql.connect(config);
console.log('Connected to SQL Server');
} catch (err) {
console.error('Error connecting to SQL Server:', err);
}
};

module.exports = { connectDB, sql };
i could not figure out what is causing the issue , have been trying to get it work since hours
vinter.
vinter.3mo ago
Can you send also projectController.js
Faisu0p
Faisu0pOP3mo ago
const mssql = require('mssql'); // Add this line at the top if it's missing
const dbConfig = require('../config/db'); // Adjust path if necessary

const projectModel = require('../models/projectModel');


// Controller to get all projects
const getAllProjects = async (req, res) => {
try {
const projects = await projectModel.getAllProjects();
res.status(200).json(projects);
} catch (err) {
console.error('Error fetching projects:', err);
res.status(500).json({ message: 'Error fetching projects' });
}
};

const getProjectById = async (req, res) => {
const projectId = req.params.id; // Get the project ID from the request params
let pool;

try {
if (!projectId) {
return res.status(400).json({ message: 'Project ID is required' }); // Check if projectId is provided
}

pool = await mssql.connect(dbConfig);

// Check if the connection is successful
if (!pool) {
return res.status(500).json({ message: 'Error connecting to the database' });
}

const result = await pool.request()
.input('id', mssql.Int, projectId) // Use parameterized query for security
.query('SELECT * FROM Projects WHERE id = @id');

// Check if project exists in the database
if (result.recordset.length > 0) {
res.status(200).json(result.recordset[0]); // Return the project details if found
} else {
res.status(404).json({ message: 'Project not found' }); // Project not found
}
} catch (err) {
// Improved error handling
if (err.code === 'ECONNREFUSED') {
console.error('Database connection refused:', err);
return res.status(503).json({ message: 'Database connection refused, please try again later' });
}

console.error('Error fetching project:', err);
res.status(500).json({ message: 'An unexpected error occurred while fetching the project' });
} finally {
if (pool) {
pool.close();
}
}
};


module.exports = { getAllProjects, getProjectById };
const mssql = require('mssql'); // Add this line at the top if it's missing
const dbConfig = require('../config/db'); // Adjust path if necessary

const projectModel = require('../models/projectModel');


// Controller to get all projects
const getAllProjects = async (req, res) => {
try {
const projects = await projectModel.getAllProjects();
res.status(200).json(projects);
} catch (err) {
console.error('Error fetching projects:', err);
res.status(500).json({ message: 'Error fetching projects' });
}
};

const getProjectById = async (req, res) => {
const projectId = req.params.id; // Get the project ID from the request params
let pool;

try {
if (!projectId) {
return res.status(400).json({ message: 'Project ID is required' }); // Check if projectId is provided
}

pool = await mssql.connect(dbConfig);

// Check if the connection is successful
if (!pool) {
return res.status(500).json({ message: 'Error connecting to the database' });
}

const result = await pool.request()
.input('id', mssql.Int, projectId) // Use parameterized query for security
.query('SELECT * FROM Projects WHERE id = @id');

// Check if project exists in the database
if (result.recordset.length > 0) {
res.status(200).json(result.recordset[0]); // Return the project details if found
} else {
res.status(404).json({ message: 'Project not found' }); // Project not found
}
} catch (err) {
// Improved error handling
if (err.code === 'ECONNREFUSED') {
console.error('Database connection refused:', err);
return res.status(503).json({ message: 'Database connection refused, please try again later' });
}

console.error('Error fetching project:', err);
res.status(500).json({ message: 'An unexpected error occurred while fetching the project' });
} finally {
if (pool) {
pool.close();
}
}
};


module.exports = { getAllProjects, getProjectById };
yes i did
vinter.
vinter.3mo ago
I think the issue is in pool = await mssql.connect(dbConfig); You're exporting { connectDB, sql }; from the db.js but sql.connect() requires a config object as far as I can see
Faisu0p
Faisu0pOP3mo ago
so how do i fix it : ( my brain is not braining anymore 😭
vinter.
vinter.3mo ago
module.exports = { connectDB, sql, config};
const {connectDB, sql, config} = require('../config/db');

////

pool = await mssql.connect(config);
const {connectDB, sql, config} = require('../config/db');

////

pool = await mssql.connect(config);
probably something like this
Faisu0p
Faisu0pOP3mo ago
trying got this error
Server running on port 5000
Connected to SQL Server
Error fetching project: TypeError: Cannot read properties of undefined (reading 'port')
Server running on port 5000
Connected to SQL Server
Error fetching project: TypeError: Cannot read properties of undefined (reading 'port')
i have ot fix protery controller tooo fixing it ... : (
Faisu0p
Faisu0pOP3mo ago
No description
Faisu0p
Faisu0pOP3mo ago
pain i did change it in the other controller too I just wanted to tell u that When i start the server it starts fine when i test the api req in the postman first time it works as expected when i 2nd time sends a req it throws that error @vinter. u still here bro ?
vinter.
vinter.3mo ago
Sorry, busy with work. Will reply when I have a moment
Faisu0p
Faisu0pOP3mo ago
okay np
vinter.
vinter.3mo ago
const dbConfig = require('../config/db');
///
pool = await mssql.connect(dbConfig.config);
const dbConfig = require('../config/db');
///
pool = await mssql.connect(dbConfig.config);
try this maybe? not sure why it would be undefined like I think what was happening before was that you were passing { connectDB, sql }; to mssql.connect(); which is expecting a config instead. Maybe the library does something weird and executes the connectDB each time or something, so the second time it fails And here that object became undefined instead so idk, probably something wrong with the exports
Faisu0p
Faisu0pOP3mo ago
@vinter. Thanks for the help i found the issue here and fixed it so , basically it was because i was breaking the connection after every request , i was using finally block which was causing it to break i just remvoed that block from everywhere and fixed the issue in this u can see in last 3 lines
vinter.
vinter.3mo ago
Oh great! Glad it works
Faisu0p
Faisu0pOP3mo ago
❤️ thanks for help though ! !close !end

Did you find this page helpful?