const express = require('express')
const bodyParser = require('body-parser')
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware')
const app = express()
app.use(bodyParser.json())
app.use(awsServerlessExpressMiddleware.eventContext())
// Enable CORS for all methods
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "*")
next()
});
// Connect to DB
const sql = require("mssql")
const config = {
server: "SERVER",
user: "USER",
password: "PASSWORD",
port: 1433,
database: "DATABASE"
}
console.log("Attemping to connect...")
let q = "SELECT * FROM QUERY"
// Async Await
async function getDB() {
console.log("Inside getDB...")
try {
let pool = await sql.connect(config)
console.log("Connected")
let item = await pool.request().query(q)
console.log(item)
sql.close()
return item;
} catch(err) {
console.log("Query did not complete.")
console.log(err.message);
sql.close();
}
}
let result = getDB();
console.log("Result: " + result)
app.get('/', function(req, res) {
res.status(200).json({result, url:req.url})
});
I am running an application using AWS amplify and I am trying to connect to an RDS database through my backend lambda function. When I check CloudWatch I get a failed connection to database. I'm not certain what the issue is because I use the exact same settings to connect using Python using the pyodbc library.
CloudWatch
var mysql = require('mysql')
var connection = mysql.createPool({
host: "localhost",
user: "root",
password: "",
database: "snappay",
port : "3306"
})
connection.getConnection((err, connection) => {
if (err) {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.error('Database connection was closed.')
}
if (err.code === 'ER_CON_COUNT_ERROR') {
console.error('Database has too many connections.')
}
if (err.code === 'ECONNREFUSED') {
console.error('Database connection was refused.')
}
}
if (connection) connection.release()
return
})
module.exports = connection
please follow this connection code hope it'll work
ref : https://github.com/vishalims095/nodeJS_Mysql/blob/developer/src/Modules/connection.js
Related
var app = require('express')();
app.get('/', (req, res) => {
var sql = require("mssql");
// config for your database
var config = {
user: 'sa',
password: 'xxxxx',
server: 'xx',
database: 'formdangky',
port :'1443'
};
(async function () {
try {
let pool = sql.connect(config)
let result1 = await pool.request()
.query('select * from dondangky')
// console.dir(result1)
// send records as a response
res.send(result1);
} catch (err) {
res.send(err)
}
})();
sql.on('error', err => {
// error handler
console.log(err);
});
});
//start listening
var port = 3000;
app.listen(port, function () {
console.log('Application started on ' + new Date());
console.log("Listening on " + port);
});
When i trying code but then the result is empty end not show something
Node JS to SQL SERVER get null empty when i trying conect with mssql from Npm https://www.npmjs.com/package/mssql#asyncawait
to get reslut from database
I have been trying to connect to mongodb via my node app on a shared hosting cpanel but it only responds with error code 503 and logs "db.collection undefined" to the console, which means the connection was not successful.
This is the database connection in db.js:
const { MongoClient } = require('mongodb');
require('dotenv').config();
let dbConnection;
module.exports = {
connectToDb: (cb) => {
MongoClient.connect(`mongodb+srv://Achifa:${process.env.PASSWORD}#cluster0.exp9r.mongodb.net/?retryWrites=true&w=majority`)
.then((client) => {
dbConnection = client.db('newsDb')
return cb()
})
.catch(err => {
console.log(err)
return cb(err)
})
},
getDb: () => dbConnection
}
This is the app connection in app.js:
const {connectToDb, getDb} = require('./db');
let db;
var port = process.env.PORT || 50500;
connectToDb((err) => {
if(!err){
var server = app.listen(port, () => console.log("connected"));
db = getDb();
}
})
I'm a beginner and try to create a rest API following this tutorial. I expected to see Server is running on port: ${PORT}, but it seems like my code can't reach it. I got no error on my terminal and it looks like this
Here are my code:
server.js
require('dotenv').config({ path: './config.env' });
const express = require('express');
const cors = require('cors');
const dbo = require('./db/conn');
const PORT = process.env.PORT || 5000;
const app = express();
app.use(cors());
app.use(express.json());
app.use(require('./api/api'));
// Global error handling
app.use(function (err, _req, res) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
// perform a database connection when the server starts
dbo.connectToServer(function (err) {
if (err) {
console.error(err);
process.exit();
}
// start the Express server
app.listen(PORT, () => {
console.log(`Server is running on port: ${PORT}`);
});
});
conn.js
const MongoClient = require('mongodb').MongoClient
const dotenv = require("dotenv")
dotenv.config()
const connectionString = process.env.MONGOURI
let db;
module.exports = {
connectToServer : function(callback) {
MongoClient.connect(connectionString, {
useUnifiedTopology: true
}, (err, client) => {
if (err) return console.error(err)
db = client.db('db-name');
console.log('Connected to Database');
return callback
});
},
getDb: function () {
return db;
}
}
api.js
const express = require("express");
const gameRoutes = express.Router();
const dbo = require('../db/conn');
gameRoutes.route("/game").get(async function (_req, res) {
const dbConnect = dbo.getDb();
dbConnect
.collection("game")
.find({}).limit(50)
.toArray(function(err, result) {
if (err) {
res.status(400).send("Error fetching listings!");
} else {
res.json(result);
}
})
})
module.exports = gameRoutes;
Can you please tell me what's wrong with my code? I really can't find why the server is not running. Thanks in advance! I'll be very grateful for your help!
In your connectToServer method you just returning the callback. But you actually need to call it as well.
So change this
return callback
to this
return callback(null);
If you want to pass the possible error from MongoClient to the callback as well, then change your connectToServer method to this :
connectToServer : function(callback) {
MongoClient.connect(connectionString, {
useUnifiedTopology: true
}, (err, client) => {
if (err) { return callback(err); }
db = client.db('db-name');
console.log('Connected to Database');
return callback(null) // no error, so pass "null"
});
}
In app.js, when express running, express will create pool connection. then pool instance can be access in other file. How to do that?
app.js
const express = require('express');
const app = express();
const port = 8080;
const mysql = require('mysql2');
const comic = require('./routes/comic');
app.use('/comics', comic);
app.listen(port, () => {
console.log(`Server is listening in ${port} port`);
const pool = mysql.createPool({
host:'localhost',
user: 'root',
password: 'test',
database: 'test'
});
exports.connection = pool.promise();
});
test.js
const {connection} = require('./app');
(async () => {
const [rows] = await connection.execute('SELECT * FROM people');
console.log(rows);
})();
I would recommend you to have a seperate db.js file that would have the connection pool and import that pool wherever necessary
In db.js
const mysql = require('mysql2');
const pool = mysql.createPool({
host:'localhost',
user: 'root',
password: 'test',
database: 'test'
});
module.exports = pool;
And in the place where u want it
let pool = require('./db');
const queryRes = (query, pool) => new Promise((resolve, reject) => {
pool.getConnection(function(err, connection) {
if(err) {
reject('Error');
}
connection.query(query, (err, results, fields) => {
if(err) {
reject('Error');
}
else{
connection.release();
resolve(results);
}
});
connection.on('error', (err) => {
reject('Error');
connection.release();
});
});
});
queryRes("Select * from test", pool).then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});
Hi I am creating node js restful api by using sqlserver database , i prepare get api when i am using that api output is shown in json format, while refreshing that browser gain its shows "Error: Global connection already exists. Call sql.close() first."error . I am adding code
var express = require("express");
var sql = require("mssql");
var app = express();
//Initiallising connection string
var dbConfig = {
user: 'sa',
password: 'India123',
server: 'localhost',
database: 'sample'
};
app.get('/login', function (req, res) {
// connect to your database
var data = {
"user": ""
};
sql.connect(dbConfig, function (err) {
if (err) console.log(err);
var request = new sql.Request();
request.query('select * from Login', function (err, result) {
if (err) console.log(err)
// send data as a response
//res.send(result.recordset);
data["user"] = result.recordset;
res.send(data);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
Please correct me code . thanks advance
// db.js
var mssql = require("mssql");
var dbConfig = {
user: 'sa',
password: 'India123',
server: 'localhost',
database: 'sample'
};
var connection = mssql.connect(dbConfig, function (err) {
if (err)
throw err;
});
module.exports = connection;
// app.js
var db = require("db");
var express = require("express");
var app = express();
app.get('/login', function (req, res, next) {
var request = new db.Request();
request.query('select * from Login', function (err, result) {
if (err)
return next(err);
var data = {};
data["user"] = result.recordset;
res.send(data);
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
Don't use sql.Connection() any more, instead use sql.ConnectionPool()
Connections
Internally, each ConnectionPool instance is a separate pool of TDS connections. Once you create a new Request/Transaction/Prepared Statement, a new TDS connection is acquired from the pool and reserved for desired action. Once the action is complete, connection is released back to the pool. Connection health check is built-in so once the dead connection is discovered, it is immediately replaced with a new one.
IMPORTANT: Always attach an error listener to created connection. Whenever something goes wrong with the connection it will emit an error and if there is no listener it will crash your application with an uncaught error.
Create pool and use connection.
const pool = new sql.ConnectionPool({ /* config */ })
Entire Article how to use pool and close pool.
https://www.npmjs.com/package/mssql
var sql = require("mssql");
const pool = new sql.ConnectionPool({
user: 'sa',
password: 'Pass#123',
server: 'SAI-PC',
database: 'Demo'
})
var conn = pool;
conn.connect().then(function () {
var req = new sql.Request(conn);
req.query("SELECT * FROM Product").then(function (recordset) {
console.log(recordset);
conn.close();
})
.catch(function (err) {
console.log(err);
conn.close();
});
})
.catch(function (err) {
console.log(err);
});