Cannot enqueue Handshake after already enqueuing a Handshake - mysql

const app = require('./app');
var mysql = require('mysql');
const server = app.listen(3000, () => {
console.log(`Express is running on port ${server.address().port}`);
});
I learning nodejs 3 day but i don't know how can i fix it i try to fix it but not work.
Someone Help me please
I don't know what i wrong. I want to insert data into mysql with pug
be like login with html and use php to select data in phpmyadmin
register in pug and data send to nodejs and node post data to mysql
I'm sorry my English and gramma so bad :(
const express = require('express');
var mysql = require('mysql');
const router = express.Router();
const app = require('../app.js');
var conn = mysql.createConnection({
host: "localhost",
user: "root",
password: "1234",
database:"project_test"
});
conn.connect(function(err) {
if (err) throw err;
console.log("Index Connection!");
});
conn.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO customer (name, address) VALUES ('Company Inc', 'Highway 37')";
conn.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
module.exports = router;

Related

Connect MySQL database with node JavaScript application

I make a node JavaScript app and deploy it on cPanel using SSH.
App is working fine without database but when I connect the app with database on cPanel (GoDaddy) it takes times and shows the message "Error establishing a database connection".
My connection code
const mysql = require('mysql');
const express = require('express');
const app = express();
var pool = mysql.createConnection({
host: 'localhost',
user: '<MY_USER_NAME>',
password: '<MY_PASSWORD>',
database: '<DB_NAME>'
});
pool.connect(function(err) {
if (err) throw err;
else{
console.log("Connected!");
}
});
module.exports = pool;
route where DB interact,but lost the connection.
app.post('/loginn', (req, res) => {
var id = req.body.id
console.log("user_id= "+id);
var sql = "select * from users where id NOT IN ('" + id + "') ";
pool.query(sql, function (err, rows) {
if (err) throw err;
else {
res.render('allusers', {
users: rows,
user_id:id
})
}
});
});
This answer is going to take the form of a debugging journey, because that's the only way I can see to get to the bottom of your issue.
Let's do a dead-simple representation of your app to make sure that you can send a query to MySQL and receive a response from a route-handler in Express. Setup your app like this:
const mysql = require('mysql');
const express = require('express');
const app = express();
const PORT = // define the PORT for your host
var connection = mysql.createConnection({
host: 'localhost',
user: '<MY_USER_NAME>',
password: '<MY_PASSWORD>',
database: '<DB_NAME>'
});
connection.connect(function(err) {
if (err) console.error(err);
console.log("Connected!");
});
app.get('/db-test', (req, res, next) => {
var id = // fill in a user_id that you know exists
var sql = `SELECT * FROM users WHERE id NOT IN ('${id}') `;
console.log(sql); // confirm you are sending the sql request you believe you should be sending
connection.query(sql, function (err, results, fields) {
if (err) console.error(err);
console.log(`results: ${results}\nfields: ${fields}`);
});
});
app.listen(PORT);
And then hit the route /db-test from your app, and see what happens. If this works, then we will have at least proved that you CAN make requests between Express and MySQL. Right now, I'm not sure you can, so I'm not sure what to debug.

Connection_refused when trying to use MySQL and node.js. When using cmd it does work

I created a server.js file which looks like this.
var express = require('express'),
app = express(),
port = process.env.PORT || 3000;
app.listen(port);
console.log('todo list RESTful API server started on: ' + port)
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "**",
password: "**",
database: "test"
});
app.get('/nodeapi/getimg',function(req,res){
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM images", function (err, result, fields) {
if (err) throw err;
console.log(result[1].image);;
});
})})
When I run this file in my command terminal I get the correct result.
When I create a http.get function like this for my ionic app:
getimg(){
var url = 'http://localhost:3000/nodeapi/getimg';
this.http.get(url).subscribe(responseData => console.log(responseData));}
I get an error saying net::ERR_CONNECTION_REFUSED. I have looked everywhere but cannot seem to find it. I am using phpmyadmin for the database. Would anyone please be so kind to explain to me what I am doing wrong.
Give this example a try. Also, do you expect more than one result from your query? If not you will want to use result[0] not 1 to get the first (and maybe only) result (located at index 0).
var express = require('express');
var cors = require('cors');
var mysql = require('mysql');
var port = process.env.PORT || 3000;
var app = express();
app.use(cors());
app.options('*', cors());
var con = mysql.createConnection({
host: "localhost",
user: "**",
password: "**",
database: "test"
});
app.get('/nodeapi/getimg', function(req, res) {
con.connect(function(err) {
if(err) throw err;
con.query("SELECT * FROM images", function(err, result, fields) {
if(err) throw err;
console.log(result[1].image);
res.send(result[1].image); // send the value back to the caller.
});
})
})
app.listen(port, function() {
console.log('CORS-enabled web server listening on port 80')
})

Node.JS, Get function & Connection to XAMPP DB doesn't work

I'm using the XAMPP software as a local DB and trying to get into the get function at the below with no success.
In addition, I can not see any console comments as well:
Web error
Node.js
Thank you for your help!!
var express = require('express');
const cors = require('cors');
var app = express();
var corsOptions=
{
origin: 'http://localhost:3000',
optionsSuccessStatus: 200,
allowHeaders: ['sessionId', 'Content-Type'],
exposedHeaders: ['sessionId'],
credentials: true,
}
app.use(cors(corsOptions));
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "apptxtproject"
});
app.get("/getnetworks"), (req,res)=>{
con.query(`SELECT * FROM appadtxt`, function (err, result, fields) {
if (err) throw err;
console.log(result)
})
}
app.listen(4000, function () {
console.log('Haydeeeeee!!!');
})
In your app.get you have a bad syntax error try this:
app.get("/getnetworks", (req, res) => {
con.query(`SELECT * FROM appadtxt`, function(err, result, fields) {
if (err) throw err;
console.log(result);
});
});

Routing to other url in node.js

I am currently working on a project where I have CRUD operation using node.js and mysql.
var mysql = require('mysql');
var express = require('express');
var session = require('express-session');
var con = mysql.createConnection({
host: "database",
user: "admin",
password: "pass",
database: "db"
});
var app = express();
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM shops where id =33", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
app.use('/shop', function(err) {
con.query("SELECT * FROM shops where id =34", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
app.listen('3000', () => {
console.log('Server started on port 3000');
});
I want to get the shops data using localhost:3000/shops and brands data using localhost:3000/brands. But i don't know how to do that because i am very new in node.js. Infact,Today i my first day. I someone gives me som demo project or some thing like this. I will be very thankful.
app.get('/brands',(req,res) =>{
//inside query
})
like...thiss

How to connect sql server to app.js file?

I have a folder called NEsql, located in a folder called sqlnames1. Inside the NEsql folder, I have the following files.
sqlcreatedb.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
/*Create a database named "mydb":*/
con.query("CREATE DATABASE names", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
sqlcreatetable.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "names"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
/*Create a table named "customers":*/
var sql = "CREATE TABLE people (id INT AUTO_INCREMENT PRIMARY KEY, firstName VARCHAR(255), lastName VARCHAR(255))";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
sqlinsertvalues.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "names"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO people (firstName, lastName) VALUES ?";
var peoplenames = [
['Vedant', 'Apte'],
['Vedant', 'Savalajkar'],
['Vinay', 'Apte'],
['Varda', 'Apte'],
['Mihir', 'Wadekar'],
['Mihir', 'Kulkarni'],
['Eesha', 'Hazarika'],
['Eesha', 'Gupte'],
['Raunak', 'Sahu'],
['Hritvik', 'Agarwal'],
['Mahima', 'Kale'],
['Shivani', 'Sheth'],
['Arya', 'Chheda'],
['Diya', 'Shenoy']
];
con.query(sql, [peoplenames], function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
});
All of these files work, as I am able to complete all the tasks and successfully receive all the corresponding console.log statements. However, I am unsure as to how I am supposed to connect these files to the app.js file located inside the sqlnames1 folder. Anyone know how to do this?
Here is my app.js file.
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
What you're trying to do could simply just be the content of the app.js file you could require your package there and run these functions. However if going that route is what you choose it you could store them in a variable and then use a module.export like so
variable_name = [desired content to export]
module.export = variable_name
If you'd like to go about building a database through separate files than your app.js you should look at the package sequelize. This is more along the lines of you're trying to do.
https://www.npmjs.com/package/sequelize
Responding to your comment if you are trying to build a db upon running app.js. You are again better off looking at an ORM of some sort that will do it better than the mysql package. With it you can import the db to your app.js and simply use
require('path to db')
then using the db how you see fit, but again building your db in this way will be difficult to do as you would have to run
node filename.js
for every single one, so again if not sequelize i would strongly recommend looking at another ORM that will get this job done for you much faster and easier. As soon as you run your app.js it will build and then run, the mysql package is not the best tool to use for what it seems you are trying to do.