Node JS to SQL SERVER get null empty when i trying conect - node.js

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

Related

node app on shared hosting cpanel cannot connect to mongodb

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();
}
})

Express can't start the server or connect to MongoDB

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"
});
}

Issue connecting to SQL Server from nodeJS

So my issue is that the program obviously isn't working, but it also isn't crashing. It's like it never executes the try or catch.
const express = require("express"),
app = express(),
sql = require("mssql"),
port = 5000 || process.env.PORT,
bodyParser = require("body-parser"),
routerBoi = express.Router();
const sqlConfig = {
user: "sa",
password: "#Strongman105",
server: "DESKTOP-RVS5F2QHSTESTSERVER",
database: "master"
};
async () => {
try {
// make sure that any items are correctly URL encoded in the connection string
await sql.connect(sqlConfig);
const result = await sql.query(`select * from Users`);
console.log(result);
} catch (err) {
console.log(err);
}
};
// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
The entirety of my output is "Listening on port 5000".
What am I doing wrong here?
(async function() {
try {
await sql.connect(sqlConfig);
const result = await sql.query(`select * from Users`);
console.log(result);
} catch (err) {
console.log(err);
}
})();
Just wrap your async function with round braces and make it self execution function. you can refer this in the official docs. https://www.npmjs.com/package/mssql#asyncawait

Reading url passed data in node.js routes

I'm passing a data of a variable in URl from an python as
response = urlopen("localhost:5000/warehouse?fruitid=103456",timeout=10);
data = json.loads(response.read().decode('utf8'));
And it reading the response in json format for further processing.
How can I write the node.js routing for posting the data which reads the passed variable value of fruitid=103456 and insert the timestamp into the database when this request occurs.
Please help me out__...
try this - i use this to parse out json responses from other sources...
import pandas as pd
data1=dict(field1=data['field1_in_response'], field2=data['field2_in_response'],...);
data1=pd.DataFrame(data1)
print(data1)
const express = require('express');
const app = express();
const port = 5000;
var mysql = require('mysql')
var squel = require("squel");
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'toor',
database: 'invoice'
});
app.get('/warehouse', (req, res) => {
let fruitid = req.query.fruitid;
let queryDashboard = "select * from fruit where fruitid ='"+fruitid +"'";
connection.query(queryDashboard, function (err, rows, fields) {
if (err) throw err
console.log('query get successful');
var result = rows.map(data => data.name);
res.send(result);
// connection.end()
})
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));`enter code here`
Here's how you could handle this kind of request in an Express/MongoDB app:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const app = express();
const port = 5000;
app.get('/warehouse', (req, res) => {
console.log('fruitid:', req.query.fruitid);
MongoClient.connect('mongodb://localhost:27017', function (err, client) {
if (err) throw err;
const db = client.db('mydatabase');
db.collection('fruits').find({ id: req.query.fruitid }).toArray(function (err, result) {
if (err) throw err;
res.json(result);
});
});
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

Error: Global connection already exists. Call sql.close() first

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);
});

Resources