I'm new to react, developing a recipe-app and I got a problem while displaying the data from MySQL database. The connection was created successfully, however, I'm not sure about how to reach the data. When I run node server.js in my terminal, I get "connected", When I visit the localhost:8080/users, I get "This site can't be reached" message and in my terminal:
`events.js:187
throw er; // Unhandled 'error' event
^
Error: Cannot enqueue Handshake after already enqueuing a Handshake.`
I'm a little stuck here. Anyone knows a solution or direct me a little bit? Thank you so much!
Server.js
const express = require('express');
const app = express();
const PORT = 8080;
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'recipe_app'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected!');
});
//creating route for the app
app.get('/users', (req, res) => {
connection.connect();
connection.query('SELECT * from users', function(err, rows, fields) {
if (!err) {
res.send(JSON.stringify(rows));
} else {
console.log('Error while performing Query.');
}
});
connection.end();
});
//making server listen to request
app.listen(PORT, () => {
console.log(`Server running at : http://localhost:${PORT}/`);
});
You're trying to reconnect to mysql after the connection has been established.
See my comments on the code below
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'recipe_app'
});
connection.connect((err) => { // This creates the connection
if (err) throw err;
console.log('Connected!');
});
And when you're trying to resolve your GET routes, you're trying to connect again
//creating route for the app
app.get('/users', (req, res) => {
connection.connect(); // reconnect here
Since you're using the default connection method, trying to connect to an already established connection will cause the driver to throw a Handshake error.
If you want to re-use the connection, store it in a variable and then re-use it in other part of your code.
If you want to manage multiple connections instead, I suggest you to look at createPool instead.
Try removing the connection.connect() and connection.end() from app.get
Related
I am very new to programming so I do apologize if this is a really simple question.
So, I have been trying to connect my React Native application to the MySQL Database using Node and Express server, but I keep on getting the following error (I have checked other stackoverflow questions as well, but nothing has helped):
Error
I have checked my host name and port number multiple times and the all the information seems to be correct. I am not sure what is wrong with the following code:
var express = require("express");
var app = express();
var mysql = require("mysql");
var bodyParser = require("body-parser");
const { application } = require("express");
app.use(bodyParser.json({ type: "application/json" }));
app.use(bodyParser.urlencoded({ extended: true }));
var connection = mysql.createConnection({
host: '127.0.0.1', // Your connection adress (localhost).
port: "3306",
user: "root", // Your database's username.
password: "", // Your database's password.
database: "birthdays", // Your database's name.
});
connection.connect(function (error) {
if (error) console.log(error);
else console.log("connected");
});
// Starting our server.
app.listen(4547, () => {
console.log("Go to http://localhost:4547/dinners so you can see the data.");
});
app.get("/users", function (req, res) {
con.query("select * from users", function (error, rows, fields) {
if (error) console.log(error);
else {
console.log(rows);
res.send(rows);
}
});
});
I run this code by typing "node fileName.js" in the terminal.
I don't know if this is helpful, but I have also connected by MySQL database to MySQL Workbench.
Any help is appreciated!
I am not sure I understand the labels properly. I get this error "blogs:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error)". I've attached a picture of my MySQL home screen.
import * as mysql from 'mysql';
import Blogs from './blogs';
export const Connection = mysql.createConnection({
host: '127.0.0.1', //I don't if this is what I am Supposed to put here
port: 3306,
user: 'suggesteventuser',
password: 'thisfakepassword',
database: 'Recomend an Adventure',
});
export const Query = (query: string, values?: Array<string | number>) => {
return new Promise<Array<any>>((resolve, reject) => {
Connection.query(query, values, (err, results) => {
if (err) return reject(err);
return resolve(results);
});
});
};
export default {
Blogs,
};
// When I try to go to this route I get this error message
router.get('/api/blogs', async (req, res) => {
try {
res.json(await db.Blogs.all());
} catch (e) {
console.log(e);
res.sendStatus(500);
}
});
Error message:
blogs:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Your database is the name of the folder in your project usually mydatabase
If you match up the code to the image you should be able to replicate a proper
connection to your database this was surprisingly hard to find so I hope this helps!
mysql:{
host: '127.0.0.1',
port: 3306,
user: 'suggesteventu...',
password: 'yourpassword
database: 'mydatabase',
}
Question: Why is my middle end server not responding after connecting to a database?
Hello, so I have a simple mysql database server running and open in mysql workbench (I ran a test and it is working), and I also have a simple middle end node app to handle and process requests. I can even run a query to make a database in mysql before the api stops responding.
The problem: after I connect to my database, my middle end end points stop working. such as my default page "/" for "hello world". I have very simple and basic node db connection code so I'm not sure why it's failing.
var express = require('express')
var app = express()
var https = require('https')
var mysql = require('mysql')
var cors = require('cors')
app.use(express.json())
var myLogger = function (req, res, next) {
console.log('LOGGED')
next()
}
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
port: '3306',
database:'mydbtest666'
});
db.connect(function (err) {
if (err) throw err;
console.log("Connected!");
db.destroy();
});
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(5000)
I am using the logger to help log commands, and it will show that the endpoint was called, but no data is being shown on my screen and again the page just loads and loads.
I thought closing/destroying the connection would work, but it is not. Would a try catch change anything??
Here's another attempt with my signup but the middle end still freezes and with this attempt it no longer connects to the database:
app.post("/users/signup", (req, res) => {
const username = req.body.username
const password = req.body.password
db.connect(function (err) {
if (err) throw err;
console.log("Connected!");
try {
db.query("INSERT INTO users (username, password) VALUES (?,?)", [username, password], (err, result) => { });
db.destroy();
} catch (err) {
console.log(err);
}
});
});
I am learning to develop server on node-js and have developed a basic get function which retrieves data from MySQL DB hosted on a ubuntu server at digitalocean.
Here's my code:
const express = require('express')
const app = express()
const mysql = require('mysql')
const Client = require('ssh2').Client;
const ssh = new Client();
const db = new Promise(function(resolve, reject){
ssh.on('ready', function() {
ssh.forwardOut(
// source address, this can usually be any valid address
'localhost',
// source port, this can be any valid port number
3333,
// destination address (localhost here refers to the SSH server)
'xxx.xxx.xxx.xxx',
// destination port
22,
function (err, stream) {
if (err) throw err; // SSH error: can also send error in promise ex.
reject(err)
// use `sql` connection as usual
connection = mysql.createConnection({
host : '127.0.0.1',
user : 'user',
password : 'pass',
database: 'mysql',
stream: stream
});
// send connection back in variable depending on success or not
connection.connect(function(err){
if (!err) {
resolve(connection)
} else {
reject(err)
}
});
});
}).connect({
host: 'xxx.xxx.xxx.xxx', //IP address where DB is hosted
port: 22, //Port refering to the IP
username: 'user', //username to loginto the host
password: 'pass' //password to log into host
});
});
//Retrieve route
app.get('/users', (req, res) => {
//console.log("Fetching user with id: " + req.params.id)
const queryString = "SELECT * FROM user"
connection.query(queryString, (err, rows, fields) => {
if(err){
console.log("Failed to query " + err)
res.sendStatus(500)
return
}
console.log("Fetch Succesful")
res.json(rows)
})
})
app.listen(3000, () => {
console.log("Server is up and listerning on port 3000")
})
When I run this code on my local machine it is able to connect to external DB and fetch the data. I have created another server at digitalocean and hosted the same code. However upon running it I get error at connection stating: UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:3306
I tried various solutions available on the platform but could not suceed.
I have written the code accoring to the documentation but still clueless what's causing the error.
Thank You.
// 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,
})