Unable to execute Sql query in node.js using MySQL - javascript

Below is my server.js file content. When I try to execute it, It takes too long and finally I am getting "Error in the query!" Although accounts table contains 1 row but still something seems to be wrong. Please can any one help me with it!
const express = require('express')
const app = express()
const mysql = require('mysql')
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'myDatabase',
port: '8090'
});
app.set('view-engine', 'ejs')
db.connect(function(error){
if(!error){
console.log('Error');
} else {
console.log('Connected');
}
})
app.get('/test', (req, res) => {
let sql ='SELECT * FROM accounts';
db.query(sql,function(error, rows, fields) {
if(!!error){
console.log('Error in the query!');
} else{
console.log('Successful query');
console.log(rows[0]);;
}
})
})
app.get('/', (req, res) => {
res.render('index.ejs')
app.on('close', function() {
db.end();
});
app.listen('3000', ()=>{
console.log('Server started on port 3000')
})
Edit:
I am getting this error:
Error in the query! Error: Cannot enqueue Query after fatal error.
at Protocol._validateEnqueue (E:\Screen Sharing App\InovantisMeets\node_modules\mysql\lib\protocol\Protocol.js:212:16)
at Protocol._enqueue (E:\Screen Sharing App\InovantisMeets\node_modules\mysql\lib\protocol\Protocol.js:138:13)
at Connection.query (E:\Screen Sharing App\InovantisMeets\node_modules\mysql\lib\Connection.js:198:25)

Related

Is there a way of solving this typeError: connection.connect is not a function in nodejs?

I am trying to connect my school project to a mysql database but I always get the error "TypeError: connection.connect is not a function". I am not quite sure how to fix it. I hope someone is able to solve this.
My index.js
const express = require('express');
const app = express();
var connection = require('./database');
app.use(express.static('public'));
app.get('/form', (req,res) =>{
res.sendFile(__dirname + '/public/index.html' );
console.log(req.url);
console.log(req.path);
})
app.listen(4000, () =>{
console.log("Server listening on port 4000");
connection.connect((err) => {
if(err) throw err;
console.log("Connected");
})
});
my database.js
let mysql = require('mysql');
module.exports = () => {
return mysql.createConnection({
host: 'localhost',
database: 'minigames',
user: 'root',
password: 'root'
})}```
connection is the value exported from the database module.
The value you assigned to module.exports there is a function that you defined.
It is a plain, ordinary function and you have no assigned a connect property to it.
I'm guessing that connect is a property on the return value of mysql.createConnection, but if you want to access that object then, you need to call the function you defined in order to get that object.
const express = require('express');
const app = express();
var connection = require('./database');
app.listen(4000, () =>{
console.log("Server listening on port 4000");
connection().connect((err) => {
if(err) throw err;
console.log("Connected");
})
});

Connecting to MySQL Database from React?

I've been having problems with connecting to a database. It is a remote database and no matter what I do, it just doesn't work! I've searched all around to no avail. I'm using React for doing so. I just want to make a simple connection and be able to run some queries. Here's the code:
db.js component:
const mysql = require('mysql');
const db = mysql.createConnection({
/*THE VALUES BELOW ARE NOT THE ONES I HAVE TO USE*/
host: '11.111.11.11',
user: 'username',
password: 'password',
port: 'port',
database: 'database'
});
module.exports = db;
server.js in my backend folder:
const express = require('express');
const db = require('./config/db');
const cors = require('cors');
const app = express();
const PORT = 3002;
app.use(cors());
app.use(express.json());
//ROUTE
app.get("/db", (req, res) => {
db.query("SELECT * FROM users", (err, result) => {
if(err) {
console.log(err);
} else {
res.send(result);
console.log(result);
console.log('Connected!');
}
});
});
app.listen(PORT, ()=>{
console.log(`Server is running on http://localhost/${PORT}/`);
});
I'm not getting anything from it, not even the logged info I asked for in the console.log()
Thanks for the help, in advance.
You have just created the connection, however you need also use the connect function to connect to your database. So you need to add a line in your server.js, (I have put a comment near the line that you missed to write.
const db = require('./config/db');
const cors = require('cors');
const app = express();
const PORT = 3002;
app.use(cors());
app.use(express.json());
db.connect(); // you missed this line
//ROUTE
app.get("/db", (req, res) => {
db.query("SELECT * FROM users", (err, result) => {
if(err) {
console.log(err);
} else {
res.send(result);
console.log(result);
console.log('Connected!');
}
});
});
app.listen(PORT, ()=>{
console.log(`Server is running on http://localhost/${PORT}/`);
});
I think you can also do this in db.js before exporting db.

Post Request express: Cannot set headers after they are sent to the client

I'm fairly new to Node.js and I am having some issues.
im working on app for learning purposes but i came across this problem
Error: Can't render headers after they are sent to the client.
i didnt know how to make it work
C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\mysql\lib\protocol\Parser.js:437
throw err; // Rethrow non-MySQL errors
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\express\lib\response.js:267:15)
at C:\Users\GameDev\Desktop\Portfolio\reciepe\routes\route.js:32:20
at Query. (C:\Users\GameDev\Desktop\Portfolio\reciepe\models\orm.js:9:9)
at Query. (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\mysql\lib\Connection.js:525:10)
at Query._callback (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\mysql\lib\Connection.js:491:16)
at Query.Sequence.end (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
at Query.ErrorPacket (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\mysql\lib\protocol\sequences\Query.js:90:8)
SQL error :
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage:
'You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near \'NULL,
\'dqdd\'\' at line 1',
sqlState: '42000',
index: 0,
sql:
'INSERT INTO authentication(username,password) VALUES NULL, \'dqdd\'' }
here is the database
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database:'reciepeapp'
});
module.exports = con
the ORM
const con = require('./db')
const orm = {
insertOne: function (values, cb) {
const sqlQuery = "INSERT INTO authentication(username,password) VALUES ?";
con.query(sqlQuery, [values],function (err, data) {
if (err) {
console.log(err)
cb(err, null);
} else {
cb(null, data);
}
});
},
}
module.exports = orm;
here is the route.js
const express = require('express');
const app = express()
const router = express.Router()
const bcrypt = require('bcrypt');
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
const orm = require('../models/orm')
router.get('/',(req,res)=>
res.render('home')
)
router.get('/login',(req,res)=>
res.render('login')
)
router.get('/register',(req,res)=>
res.render('register')
)
router.post("/register", function (req, res) {
values = [
username = req.body.username,
password = req.body.password
];
orm.insertOne(values, function(error) {
if (error) {
return res.status(401).json({
message: 'Not able to add'
});
}
return res.json({
username: values.username,
password:values.password
});
});
});
module.exports = router
index.js
const express = require('express');
const app = express()
const bodyParser = require("body-parser");
const indexRouter = require('./routes/route')
const con = require('./models/db')
con.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var exphbs = require('express-handlebars');
console.log(__dirname)
app.use('/',express.static(__dirname + '/public'));
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.use('/',indexRouter)
const PORT = 5000;
app.listen(PORT,()=>console.log('it started on 5000'))
May I know what is wrong with my code?
The problem is in your orm file. There the callback is getting called twice(in case err is true/has a value), which in-turn calls the res.json twice. Try changing the below
con.query(sqlQuery, [values],function (err, data) {
if (err) {
cb(err, null);
} else {
cb(null, data);
}
});

Nodejs Connect with SQL not connecting

I am trying to connect to MS SQL DB using Node JS But I am getting the following error.
{ ConnectionError: Login failed for user 'Gurpanth'.
at ConnectionError not connected
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
GetData(function (recordSet) {
res.render('index', {product: recordSet})
});
});
var Connection = require('tedious').Connection;
var config = {
userName: "Gurpanth",
password: "windowspassword",
server: "GURPANTH",
options: {
database: "NodeJSDb",
encrypt: true,
}
};
var connection = new Connection (config);
connection.on('connect', function(err){
console.log(err);
if(err!=null){
console.log("not connected");
}
else{
console.log("Connected")
connection.close();
};
});
module.exports = router;
The error message you gave indicates that your username and/or password are not correct. Does that user exist in SQL Server?

Unable to Connect to MSSQL from NODEJS with SSL

I am trying to connect to Sql Server Database using Node.js
Below is the code :
var express = require('express');
var sql = require('mssql');
var app = express();
app.get('/', function (req, res) {
var config = {
server: 'server',
database: 'database',
user: 'user',
password: 'password',
options: {
encrypt: true,
trustServerCertificate:false
}
};
sql.connect(config, function (err) {
if (err) console.log(err);
var request = new sql.Request();
console.log("preparing request");
request.query("some query").then(function (recordSet) {
if (err) console.log(err);
res.send(recordset);
});
});
});
app.listen(8080);
I get the log: "preparing request". After that nothing happens. There isn't any error log either.
In Java I connect to my DB using following URL:
jdbc:jtds:sqlserver://servername;SSL=request

Categories

Resources