How to connect node.js to MySQL - javascript

I am trying to connect node.js to MySQL and failed. I have installed MySQL and relevant libraries. How do I resolve this error? Also, if I want to get data to react-native, how should I go about doing it?
const express = require('express');
const mysql = require('mysql');
const connection = mysql.createPool({
host : '*****',//aws db endpoint/MySQL hostname
user : 'administrator', // username of MySQL connection
password : '*****', //pw of MySQL db
database : 'database_3' // name of database to be used
});
const app = express();
app.get('/User', function (req, res) {
connection.getConnection(function (err, connection) {
connection.query('SELECT * FROM User', function (error, results, fields) {
if (error) throw error;
res.send(results)
});
});
});
// Starting our server.
app.listen(3306, () => {
console.log('Go to http://localhost:3306/User');
});
The error msg received :
events.js:174
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::3306
at Server.setupListenHandle [as _listen2] (net.js:1279:14)
at listenInCluster (net.js:1327:12)
at Server.listen (net.js:1414:7)
at Function.listen (C:\Users\Irvin\my-new-project\node_modules\express\lib\application.js:618:24)
at Object.<anonymous> (C:\Users\Irvin\my-new-project\route.js:39:5)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
Emitted 'error' event at:
at emitErrorNT (net.js:1306:8)
at process._tickCallback (internal/process/next_tick.js:63:19)
at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

Error: listen EADDRINUSE: address already in use :::3306
This means that the port 3306 is already in use, try changing it to another port or stop the process running on that port.
// Lets change 3306 to 3307
app.listen(3307, () => {
console.log('Go to http://localhost:3307/User');
});
If you want to stop the process on this port here is how to do it on linux

3306 is the default mysql port. Don't use that port for a server if you already have mysql running.
Don't stop the process on that port otherwise mysql will stop running, unless you're running it in another port, which is not your case.
app.listen(3000, () => {
console.log('Go to http://localhost:3306/User');
});

Hi since you are running mysql, it runs on port 3306 by default. Since you are tryung to start your express app on the same port, you get this error. You need to start your express application on any other port.

Your nodeJs application is using same port with MySQL .
// Starting our server.
app.listen(3306, () => {
console.log('Go to http://localhost:3306/User');
});
That app.listen(3306) is your nodeJs application listening port,
your current MySQL listening port is also 3306 ,
so your nodeJs application throw an error
Error: listen EADDRINUSE: address already in use :::3306
Means the port 3306 is already in use .
You should change your nodeJs application listening port like 8080 or 8090,
For example :
const express = require('express');
const mysql = require('mysql');
const connection = mysql.createPool({
host : '*****',//aws db endpoint/MySQL hostname
user : 'administrator', // username of MySQL connection
password : '*****', //pw of MySQL db
database : 'database_3' // name of database to be used
});
const app = express();
app.get('/User', function (req, res) {
connection.getConnection(function (err, connection) {
connection.query('SELECT * FROM User', function (error, results, fields) {
if (error) throw error;
res.send(results)
});
});
});
// change this port to 8090
app.listen(8090, () => {
console.log('Go to http://localhost:3306/User');
});

Related

Can't connect to remote db (Hostinger)

I've been having this error for a long time and I can't solve it. I have made my project locally, connecting to my database locally. Once finished I wanted to migrate my database manually since it is small to my hosting provider.
I have created the database, I have given it permissions to connect remotely and I have also checked that the connection data is correct.
A curiosity is that through mysql workbench it has allowed me to connect, the problem is clearly with my code, I am working with NodeJS (express). Another curiosity is that it appears to me as if I have successfully connected and 30 seconds later it gives me the following error:
Node.js v18.12.0
[nodemon] app crashed - waiting for file changes before starting...
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Listen on port 3000
Connection success!
node:events:491
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (node:internal/stream_base_commons:217:20)
Emitted 'error' event on Connection instance at:
at Connection._handleProtocolError
(C:\Users\M\Desktop\Proyect\node_modules\mysql\lib\Connection.js:423:8)
at Protocol.emit (node:events:513:28)
at Protocol._delegateError
(C:\Users\M\Desktop\Proyect\node_modules\mysql\lib\protocol\Protocol.js:398:10)
at Protocol.handleNetworkError
(C:\Users\M\Desktop\Proyect\node_modules\mysql\lib\protocol\Protocol.js:371:10)
at Connection._handleNetworkError
(C:\Users\M\Desktop\Proyect\node_modules\mysql\lib\Connection.js:418:18)
at Socket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
errno: -4077,
code: 'ECONNRESET',
syscall: 'read',
fatal: true
}
Node.js v18.12.0
[nodemon] app crashed - waiting for file changes before starting...
This is my connection script:
const mysql = require('mysql')
const connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE
});
connection.connect((error) => {
if(error){
console.log('The connection error is: ' + error)
return;
}
console.log('Connection success!')
})
module.exports = connection;
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
// Now use the connection to do stuff
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Result: " + result);
});
});
You don't show the rest of your code, but you're not doing any query in that callback function, just outputting success. You need to do stuff inside that callback, or change the way you're exporting the connection. Have a look at createPool, and getConnection as I'm guessing you're actually wanting a persistent connection to your database?

I keep getting an error in my terminal, "error address already in use :::5000"

I'm following a node.js crash course and I get to the part where we are creating a server, but for some reason every time I try to run node index which is my js file name I'm getting the error:
address already in use :::5000
I've looked through similar problems and tried to kill that specific port but nothing seems to work.
if (req.url === '/') {
fs.readFile(
path.join(__dirname, 'public', 'index.html'),
(err, content) => {
if (err) throw err;
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content);
}
);
}
const PORT = process.env.PORT || 5000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
node index
node:events:504
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::5000
at Server.setupListenHandle [as _listen2] (node:net:1330:16)
at listenInCluster (node:net:1378:12)
at Server.listen (node:net:1465:7)
at Object.<anonymous> (/Users/zacdistant/Documents/GUIDES AND TUTORIALS/Node JS Crash Course/index.js:91:8)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1151:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1357:8)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'EADDRINUSE',
errno: -48,
syscall: 'listen',
address: '::',
port: 5000
}
If you are on a Mac, port 5000 and 7000 are already used by the Control Center with the AirPlay reveicer:
lsof -i :5000
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
ControlCe 479 **** 26u IPv4 0xa2d0e96b616f779d 0t0 TCP *:commplex-main (LISTEN)
ControlCe 479 **** 27u IPv6 0xa2d0e96693d0bc65 0t0 TCP *:commplex-main (LISTEN)
To solve the issue you have to either change the port you use in your server like const PORT = process.env.PORT || 9000;, or turn off the AirPlay receiver. Also, if you want to check before hand is the port free, run netstat -anv -p tcp.
As #jamomani explained Mac uses port 5000 and 7000 that are used by the Control Center with the AirPlay receiver
To solve the issue you have to either change the port you use in your server like const PORT = process.env.PORT || 9000;, or turn off the AirPlay receiver. Also, if you want to check before hand is the port free, run netstat -anv -p tcp.

how to run an ExpressJS application

Nothing seems to work except the "throw new Error" in my code, I have installed all the necessary packages I'm sure. I am getting no errors in other places of my code. I can't seem to find the problem. Hoping someone knows how to solve this.
const express = require('express'); // we're making an ExpressJS App
const bodyParser = require('body-parser'); // we'll use body-parser extensively
//const port =3000
const app = express(); // create the ExpressJS app
// parse the different kinds of requests (content-type) the app handles
// use the "use" method to set up the body-parser middlewear
app.use(express.json()) // application/json
app.use(express.urlencoded({ extended: true })) // application/x-www-form-urlencoded
// Set up Mongoose and our Database connection
const dbConnect = require('./config/AtlasConnect.js');
const mongoose = require('mongoose');
// Set up connection to the database
mongoose.connect(dbConnect.database.url, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log("Successfully connected to the MongoDB database");
}).catch(err => {
console.log('Unable to connect to the MongoDB database', err);
process.exit();
});
throw new Error("NOT WORKING!");
// // create our test route (reply by sending a JSON message as response)
// app.get('/', (req, res) => {
// res.json({"message": "My Phone Shop App. Use the app to manage your favourite s!"});
// });
require('./app/routes/Users.routes.js')(app);
// listen for requests on port 3000
app.listen(3000, () => {
console.log("Server listening on port 3000");
});
This is the error I get in terminal:
PS C:\Users\jaffe\Documents\assignment-06-17518623> node assignment-06.js
C:\Users\jaffe\Documents\assignment-06-17518623\assignment-06.js:44
throw new Error("NOT WORKING!");
^
Error: NOT WORKING!
at Object.<anonymous> (C:\Users\jaffe\Documents\assignment-06-17518623\assignment-06.js:44:7)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
Line throw new Error("NOT WORKING!"); always throws exception, and stops code execution.
See documentation https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Statements/throw

Object #<MongoClient> has no method 'open'

I've been trying to make a simple site with Node.js, Express.js, and MongoDB. I'm new to these technologies and have been having problem set up the database
Here is snippet of code in my index.js file:
var http = require('http'),
express = require('express'),
path = require('path'),
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
CollectionDriver = require('./collectionDriver').CollectionDriver;
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
var mongoHost = 'localHost';
var mongoPort = 27017;
var collectionDriver;
var mongoClient = new MongoClient(new Server(mongoHost, mongoPort));
mongoClient.open(function(err, mongoClient) {
if (!mongoClient) {
console.error("Error! Exiting... Must start MongoDB first");
process.exit(1);
}
var db = mongoClient.db("MyDatabase");
collectionDriver = new CollectionDriver(db);
});
After I try to run node index.js in terminal, it says the following:
js-bson: Failed to load c++ bson extension, using pure JS version
/Users/username/dev/ga-final/index.js:31
mongoClient.open(function(err, mongoClient) { //C
^
TypeError: Object #<MongoClient> has no method 'open'
at Object.<anonymous> (/Users/username/dev/ga-final/index.js:31:13)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
What is wrong? Why can't I call open? Can you help me fix this? thanks!
This is happening may be because you are using new version of mongodb it is working fine after I use mongodb driver version 1.4.
npm install mongodb#1.4.x
Take a look at the mongodb docs. Your mongoClient object is not what you think it is, and that why there isn't an open() method available.
Make your example code look more like theirs:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// 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");
db.close();
});

Cannot get my file to display through Node.js

I'm having problems with my node server. I'm trying to gather data from my coffees.js file which is in a routes folder by linking it to my server.js file. Both my server.js file and routes folder containg the coffees.js file are in my nodeservers folder. When I run the server.js (which is probably the problem as I think it is coded wrong) I get the following error:
Server running at http-00000000-:8080/
Listening on port 8080...
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:904:11)
at Server._listen2 (net.js:1042:14)
at listen (net.js:1064:10)
at Server.listen (net.js:1138:5)
at Function.app.listen (/node_modules/express/lib/application.js:533:24)
at Object.<anonymous> (/home/ec2-user/nodeservers/simpleserver.js:19:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
[ec2-user#ip-10-74-151-139 nodeservers]$ ^C
[ec2-user#ip-10-74-151-139 nodeservers]$
My simpleserver.js file looks like this:
// Load the http module to create an http server.
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8080);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8080/");
var express = require('express'),
coffees = require('./routes/coffees');
var app = express();
app.get('/coffees', coffees.findAll);
app.get('/coffees/:id', coffees.findById);
app.listen(8080);
console.log('Listening on port 8080...');
Anyone able to tell me whats wrong?
Remove either
server.listen(8080) or app.listen(8080).
I think you want to use express, so remove the first.

Categories

Resources