Error when connecting mysql database with node js - html

I am using Node JS and I am trying to connect to a mysql database. It keeps getting disconnected.When I run npm start,error shows as follows
D:\face-api.js\face-api.js\examples\FaceLogInBackend\app.js:26
app.use( bodyParser.json() ); // to support JSON-encoded bodies
^
TypeError: Cannot read property 'use' of undefined
at Object. (D:\face-api.js\face-api.js\examples\FaceLogInBackend\app.js:26:5)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
Code in app.js is as belows
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'bookstore'
});
connection.connect(function(err) {
if (err) throw err
console.log('You are now connected...')
})

You need this
var mysql = require('mysql');
// instead of storing the result in a variable, just make the connection,
mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'bookstore'
});
// now connect to mysql
mysql.connect(function(err) {
if (err) throw err
console.log('You are now connected...')
})

First off check you have something like this declared on top of file
var app = express();

you can use the below code to connect to the MySQL. It works fine.
const express = require('express'),
app = express(),
bodyParser = require('body-parser');
port = process.env.PORT || 3000;
const mysql = require('mysql');
// connection configurations
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'bookstore'
});
// connect to database
connection.connect(function(err) {
if (err) throw err
console.log('You are now connected...')
})
app.listen(port);
console.log('API server started on: ' + port);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

Related

Getting PROTOCOL_PACKETS_OUT_OF_ORDER in MySQL Node.js connection

I am an absolute newbie to Node.js. I am trying to create a MySQL database and connect it to a node.js server and build APIs.
Here's my db.config.js:
const mysql = require('mysql');
//local mysql db connection
const dbConn = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'node_mysql_crud_db'
});
dbConn.connect(function(err) {
if (err) throw err;
console.log("Database Connected!");
});
module.exports = dbConn;
And here's my server.js:
const express = require('express');
const bodyParser = require('body-parser');
// create express app
const app = express();
// Setup server port
const port = process.env.PORT || 3306;
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))
// parse requests of content-type - application/json
app.use(bodyParser.json())
// define a root route
app.get('/', (req, res) => {
res.send("Hello World");
});
// Require employee routes
const employeeRoutes = require('./src/routes/employee.routes')
// using as middleware
app.use('/api/v1/employees', employeeRoutes)
// listen for requests
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
When I run nodemon server, I get the following error:
/Users/mac/Flutter_Projects/NodeMysqlCrudApp/config/db.config.js:12
if (err) throw err;
^
Error: Packets out of order. Got: 80 Expected: 0
code: 'PROTOCOL_PACKETS_OUT_OF_ORDER',
fatal: true
I have added max_allowed_packet=500M in my.cnf file and yet I continue to receive the error.
How to resolve this issue?

How to connect with mysql in config file?

What im trying to do is to connect MySQL database in my project in the config file.
config/db.js
const mysql = require('mysql')
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'mydatabase'
})
const connectDb = async () => {
const conn = await connection.connect(function (err) {
if (err) {
return console.error("error: ", err.message);
}
console.log("Connected to MySql server");
});
};
server.js
const connectDB = require("./config/db");
connectDB();
I have done this by fare and in my terminal is shown this error: TypeError: connectDb is not a function
How can I connect MySQL in the config file?
you'll need to export the connection verb, and delete the whole "connectDb" function
config/db.js
const mysql = require('mysql')
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'mydatabase'
})
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
server.js
const database = require("./config/db");
database.queryOrAnythignElse();
You'll probably want to learn again the basics of js and what is module.exports and etc...

Express taking forever to load mySQL query?

I'm trying to query a single line from a 28k record database as a test but it isn't going through but when I load up 'localhost:3001/api/get' it stays loading, even though my connection says success? Is it actually even connecting to the db?
my data bases schema is:
id | state_name | city
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const mysql = require('mysql');
const cors = require('cors');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended:true}));
app.get('/api/get', (req, res)=>{
const sqlGet = "SELECT city FROM state_city city = 'Chicago'";
db.query(sqlGet, (err, res)=>{
console.log("success");
});
});
app.listen(3001, ()=>{
console.log("running on port 3001");
});
First you must make server running. Remove that API route you had set before running server.
app.listen(3001, ()=>{
console.log("running on port 3001");
});
Now you must create database connection. Create new file dbconn.js
var mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
Now create new connection:
var new_connection = mysql.createPool(
db
);
new_connection.on('connection', function (connection) {
console.log('DB Connection established');
connection.on('error', function (err) {
console.error(new Date(), 'MySQL error', err.code);
});
connection.on('close', function (err) {
console.error(new Date(), 'MySQL close', err);
});
});
// export connection
module.exports = new_connection;
Include that connection in other file:
var db_connection = require('../dbconn');
db_connection.query(query, params, function (error, results, fields) {
//Do your query
});
Read about project structure to make your code easy to edit.

Error in delete DB record using Node.JS and MYSQL

I'm performing CRUD operations using MYSQL and NodeJS express. Their error in deleting a record from DB, I don't know why I was getting a problem as i have copied the delete query from SQL where it is working properly. Here it is 'DELETE FROM tblltest WHERE id=?'. I manually add 'id' like 'DELETE FROM tblltest WHERE id=2' then it will delete the record from DB. Please help me out to solve this issue. Here are my lines of code.
var express = require('express');
var mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'sampledb'
});
app.delete('/:id' , function(req , resp) {
connection.query('DELETE FROM `tblltest` WHERE `id`=?' , function(error , rows , fields){
if(!error){
console.log('Successful deleted!! \n');
resp.json(rows);
}else{
console.log('Error in deleting');
}
});
})
app.listen(1337);
You need to access the id route parameter in your delete API Node method, and then also bind this id value to the delete query:
app.delete('/:id', function(req, resp) {
var id = req.params.id;
connection.query('DELETE FROM tblltest WHERE id = ?', [id],
function(error, rows, fields) {
if (!error) {
console.log('Successful deleted!! \n');
resp.json(rows);
}
else {
console.log('Error in deleting');
}
});
})
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');
//start mysql connection
var connection = mysql.createConnection({
host : 'localhost', //mysql database host name
user : 'root', //mysql database user name
password : '', //mysql database password
database : 'sampledb' //mysql database name
});
connection.connect(function(err) {
if (err) throw err
console.log('You are now connected...')
})
//end mysql connection
//start body-parser configuration
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
//end body-parser configuration
//create app server
var server = app.listen(1337, "127.0.0.1", function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
});
//rest api to delete record from mysql database
app.delete('/employees', function (req, res) {
console.log(req.body);
connection.query('DELETE FROM `tblltest` WHERE `id`=?', [req.body.id], function (error, results, fields) {
if (error) throw error;
res.end('Record has been deleted!');
});
});

Woking with node.js and mysql

// So I am using mysql with node and express framework and the first time I created a test example everything worked fine. But then I tried to create a second project and now the routing seems to not being read.
And the respond back I get is:
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Server started on port 8000
mysql connected...
//I am also supposed to get the result back:
OkPackege{...
...
...
...
}
//But I am not getting it. Any Ideas...? thanks.
The scrips that i have are as follow:
const express = require('express');
const mysql = require('mysql');
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'LEoking1987'
//database : 'nodesql'
});
db.connect((err) => {
if(err){
throw err;
}
console.log('mysql connected...');
});
const app = express();
// Creates satabase if it does not exist yet.
app.get('/createdb',(req,res) => {
let sql = 'CREATE DATABASE nodesql';
db.query(sql, (err, result) => {
if(err) throw err;
console.log(result);
res.send('Database created...');
});
});
app.listen('8000',()=>{
console.log('Server started on port 8000');
});
add debug: true in your mysql connection params like
mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'LEoking1987'
database: 'nodesql'
debug: true,
})