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);
});
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 want to create a node.js app that will pull data from a database and send it to a Google Chatbot. This is the app that queries my database, I have another file that will send the data to Google Chatbot. However, running the code to get the data gives me an invalid argument error.
What am I doing wrong?
enter image description here
var sql = require('mssql');
var DailySummary = require();
DailySummary.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
var config = {
user: 'sa',
password: 'password',
server: 'localhost',
database: 'SupportCaseMonitor'
};
sql.connect(config, function (err) {
if (err) console.log(err);
var request = new sql.Request();
request.query('SELECT * FROM Message_DailySummary', function (err, recordset) {
if (err) console.log(err)
res.send(recordset);
});
});
});
var server = DailySummary.listen(5000, function () {
console.log('Server is running..');
});
function exitProcess() {
process.exit(0);
});
The problem here:
var DailySummary = require();
Likely what you meant to write was instead:
const express = require('express');
const DailySummary = express();
I have made a basic fullstack website using mssql and express. Originally the get routes worked but after implementing the post route they have stopped.
I believe I am receiving a cors error which is.
Proxy error: Could not proxy request /admin-view-users from localhost:3000 to http://localhost:5000/.
[1] See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).
my server.js
const express = require("express");
const sql = require("mssql");
var cors = require("cors");
const path = require("path");
var bodyParser = require("body-parser");
const port = process.env.PORT || 5000;
const app = express();
app.use(cors());
app.use(express.json());
const config = {
user: "sas",
password: "Mypassword456",
server: "DEVSQL_2014", // You can use 'localhost\\instance' to connect to named instance
database: "TestDBWebsite"
};
//AdminView users just pulls the users from the database
app.get("/admin-view-users", cors(), function(req, res) {
// connect to your database
sql.connect(config, function(err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query("select * from Users2 ", function(err, recordset) {
if (err) console.log(err);
// send records as a response
res.json(recordset);
res.end();
});
});
});
app.get("/admin-view-users", function(req, res) {
// connect to your database
sql.connect(config, function(err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query("select * from Users2 ", function(err, recordset) {
if (err) console.log(err);
// send records as a response
res.json(recordset);
res.end();
});
});
});
app.get("/user-questions", function(req, res) {
// connect to your database
sql.connect(config, function(err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query("select * from Questions ", function(err, recordset) {
if (err) console.log(err);
// send records as a response
res.json(recordset);
});
});
});
//
var jsonParser = bodyParser.json();
app.use(express.bodyParser());
app.post("/admin-Add-Users", jsonParser, function(request, response) {
var email = req.body.email;
var password = req.body.password;
var request = new sql.Request();
// query to the database and get the records
console.log(email, password); // your JSON
// echo the result back
console.log(request.body);
request.query(
"insert into Login (email, password) values ('" +
email +
"','" +
password +
"')",
function(err, recordset) {
if (err) console.log(err);
}
);
response.send({ message: "Success" });
});
app.listen(port, () => `Server running on port ${port}`);
I have included "app.use(cors());" which I assumed woudl resolve this but it has not.
Please advice if you can .
The first thing that comes up to my mind is the double use of CORS.
You are putting it uptop in the middleware stack and then calling it again in here:
app.get("/admin-view-users", cors(), function(req, res) {
Please try using this only once:
https://www.npmjs.com/package/cors
I am trying to perform an INSERT into my SQL Server through my NODE.js server
but it is not working.
I believe it is not a connection problem because (as I will demonstrate at the end of the post) I did a select that worked, so I must be making some mistake in the node.js code.
This is the first javascript system I create.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', function (req, res) {
var body = req.body;
var sql = require("mssql");
console.log("C1");
sql.connect('mssql://login:pswd#serv/db', function (err) {
if (err) console.log(err);
// create Request object
console.log("Connected!");
var insert = "INSERT into dbo.WIDS_API_TEST (Programm, ID, Titlw) VALUES ('Teste 1 2 3 ', '39', 'Finance')"
// query to the database and get the records
sql.query(insert, function (err, result) {
if (err) console.log(err)
// send records as a response
console.log("1 record inserted");
});
});
});
//var server = app.listen(5000, function () {
// console.log('Server is running..');
//});
What am I doing wrong? Because the INSERT did not even show my console.logs =/
When I performed a test doing a select it worked, so
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
/* var config = {
user: 'papercut',
password: 'Portage.2018',
server: 'devsqlcl2:1433',
database: 'AgrM6',
port: "1433",
dialect:",ssql",
dialectOptiond:"SQLEXPRESS"
};*/
// connect to your database
sql.connect('mssql://login:pswd#server:1433/database', function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from dbo.balance_papercut', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
This SELECT statement worked.
I'm trying to use MongoDB with Node/Express. I made the official example work:
var express = require('express')
var MongoClient = require('mongodb').MongoClient
var assert = require('assert')
var app = express()
// Connection URL
var url = 'mongodb://localhost:27017/myproject'
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err)
console.log("Connected correctly to server")
insertDocuments(db, function() {
db.close()
})
})
var insertDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents')
// Insert some documents
collection.insertMany([
// Some code
], function(err, result) {
// Some code
callback(result)
})
}
app.get('/insert-document', function(req, res) {
// res.send()
})
How can I make it so that Mongo is available inside Express' HTTP methods? For instance, to use insertDocuments() inside app.get('/insert-document', function(req, res)?
EDIT (full server.js file):
var express = require('express')
// var PouchDB = require('pouchdb')
var MongoClient = require('mongodb').MongoClient
var assert = require('assert')
var webpack = require('webpack')
var config = require('./webpack.dev.conf')
var app = express()
var compiler = webpack(config)
// Connection URL
var url = 'mongodb://localhost:27017/myproject'
// Use connect method to connect to the Server
var db
MongoClient.connect(url, function(err, db) {
assert.equal(null, err)
console.log("Connected correctly to server")
db = db
})
var insertDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents')
// Insert some documents
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
assert.equal(err, null)
assert.equal(3, result.result.n)
assert.equal(3, result.ops.length)
console.log("Inserted 3 documents into the document collection")
callback(result)
})
}
// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())
// serve webpack bundle output
app.use(require('webpack-dev-middleware')(compiler, {
publicPath: config.output.publicPath,
stats: {
colors: true,
chunks: false
}
}))
// enable hot-reload and state-preserving
// compilation error display
app.use(require('webpack-hot-middleware')(compiler))
app.get('/docs', function(req, res) {
// res.send()
insertDocuments(db, function() {
db.close()
})
})
app.listen(8080, 'localhost', function (err) {
if (err) {
console.log(err)
return
}
console.log('Listening at http://localhost:8080')
})
I get
TypeError: Cannot read property 'collection' of undefined
at insertDocuments (/home/alex/node/project-mongo/build/dev-server.js:24:22)
Refer codes here, save the connection db as one global variable, sample codes as below.
var db;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err)
console.log("Connected correctly to server")
db = db;
// Start the application after the database connection is ready
app.listen(3000);
console.log("Listening on port 3000");
});
// Reuse database object in request handlers
app.get('/insert-document', function(req, res) {
// insertDocuments() could invoked here.
});