Node.js with mySQL -> Connection refused to 127.0.0.1 : 3306 - javascript

First, I have this code here for the server, which works perfectly
var app = require('express')();
var mysql = require('mysql');
app.get('/', function (req, res) {
res.sendFile(__dirname + "/start.html");
});
app.listen(3000);
But, if I try to create a connection to a database, it says that the connection is refused to 127.0.0.1 : 3036
var db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'user_data'
});
db.connect();
I am using XAMMP :
Click here -> MySQL / Apache
So what is the problem? I don't understand. I also get this error when I try to access phpMyAdmin :
Link to the error

You need to specify a port as your database is listening on a non standard port
var db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'user_data',
port: 3036
});
db.connect();
For phpMyAdmin, you need to find config.inc.php in phpMyAdmin's top level directory and edit the line where it says
$cfg['Servers'][$i]['port']
to the port you are using. And you need to change
$cfg['Servers'][$i]['host']
to 127.0.0.1 instead of localhost, because:
If you use localhost as the hostname, MySQL ignores this port number and connects with the socket, so if you want to connect to a port different from the default port, use 127.0.0.1 or the real hostname in $cfg['Servers'][$i]['host'].
Documentation on phpMyAdmin

Related

Error: listen EADDRINUSE: address already in use :::3306

I'm trying to create a log system with MySQL and Node.JS. But I'm getting the error you see below, I'm still actively looking for a solution, but I couldn't find it. And I decided to ask you.
.env
DB_HOST = 127.0.0.1
DB_USER = newuser
DB_PASSWORD = password123#
DB_DATABASE = userDB
DB_PORT = 3306
PORT = 3000
Node.js
const express = require('express');
const app = express();
const mysql = require('mysql');
require('dotenv').config({path: './dbInfo.env'})
const db = mysql.createPool({
connectionLimit: 100,
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
port: process.env.DB_PORT
})
db.getConnection( (err, connection) => {
if (err) throw (err)
console.log("DB connected succesful:" + connection.threadId)
})
const port = process.env.DB_PORT
app.listen(port,
() => console.log('Server started on port ${port}...'))
console.log(process.env.DB_PASSWORD)
It seems the Port 3306 is already used. 3306 is the MySQL standard port, so most likely your MySQL instance is already running which you would want.
You can only have one service running behind a port. That's the purpose of ports to direct traffic to the process that can deal with that traffic or expects that traffic.
To resolve the issue use const port = process.env.PORT instead of const port = process.env.DB_PORT. Your Express server then runs on port 3000 and your MySQL server on port 3306.
FYI: You should specify some default values (or errors) in case the environment variables are not set. You might have set them here with your .env file both you might wanna run the server in another environment some day and you'll forget to configure something and wonder why your server is crashing.
One quick and easy solution that will do for starters could be to use logical OR (||). This will set the port set in the environment variables or the default value of 3000.
// Mocking process.env
const process = { env: {}}
// process.env.PORT is not defined here so the default value will be used
const port = process.env.PORT || 3000;
console.log(`Port: ${port}`)
You might also be interested in the dotenv npm package.

I can't access to mySQL with node js anymore

I have updated my node version, and now I can't access to my DB with my app. I tried many things:
-Change rout to 127.0.0.1.
-add my port number 3306
-add socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
-kill node running
And probably others, but I always have an error. Actually, I have this one while running this code.
Error:
disconnected
error: connect ECONNREFUSED ::1:3306
My code who was working before:
const mysql = require('mysql');
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "discord"
});
if (db.state === 'disconnected') {
db.connect(function (err) {
if (err) { return console.error('error: ' + err.message); }
console.log('Connected to the MySQL server.');
});
}
console.log(db.state);
module.exports = db
My issue was the version of discord.js because I have updated it as well. I've changed it in my package.json for the one I used before and everything is working well. It will be hard to update all my app to the new version. If you have any recommendation to update it easily without running into multiple issues, I'm here !

how to make a folder of images accessible in node.js mysql

i wrote an api node.js mysql and i created a folder called images in the same directory with index.js file , but when go to http://localhost:3000/images/bike.png a message says that Cannot GET /images/bike.png
the same message also for Cannot GET /images
my index.js file
/* RESTFUL SERVICES BY NODEJS */
var express = require('express');
var mysql = require('mysql');
var bodyParser = require('body-parser');
//connect to mysql
var con = mysql.createConnection({
host: 'localhost' ,
user: 'root' ,
password: '',
database: 'nodeapp'
})
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static('images/'));
//connect to database
con.connect((err) =>{
if(err) throw err;
console.log('Mysql Connected...');
});
/Server listening
app.listen(3000,() =>{
console.log('Server started on port 3000...');
});
how to make images folder accessible and to go to the bike.png by url
Firstly you should remove the trailing slash in app.use(express.static('images/')); as #ptothep already mentioned.
If you don't indicate a route for static assets they will be accessible from a root URL like this localhost:3000/bike.png.
If you wish to map images folder to /images then indicate this route like this:
app.use('/images', express.static('images'));
See Static files

How can I make my localhost server available from external requests?

I'm running a simple nodejs server on my localhost on port :3434
const cors = require('cors');
const app = require('express')();
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.get('/ping/:anystring', (req, res) => {
console.log(req.params['anystring']);
res.send({
anystring: req.params['anystring']
})
});
app.listen(3434);
and I'd like to perform some ajax call from a website of mine.
I tried to configure the router port forwarding like so:
- name service: mylocalserver
- porta ragnge: 3434
- local ip: 192.168.1.19
- local port: 3434
- protocol: BOTH
but when I do
fetch(publicIP:3434/ping/hello).then(res => {
console.log(res);
})
I get error 404
Might anyone help me telling what I'm doing wrong?
You can't access your localhost server outside of your LAN unless you create a tunnel. I use ngrok.
There is an npm package for ngrok, but I couldn't get that one working, so I just manually start the server from terminal whenever I need to test an API.
Also you'll need http.
add this to your app.js:
const http = require('http');
const newPort = //your port here (needs to be a different port than the port your app is currently using)
const server = http.createServer(function(req, res) {
console.log(req); //code to handle requests to newPort
res.end('Hello World);
});
app.listen(newPort, function() {
console.log(`ngrok listening on ${newPort}`);
});
Now in terminal, after installing ngrok, use this ngrok http newPort where newPort = your port
You can view requests sent to your server by going to localhost:4040 (this might change depending on your system)
To send a request to your localhost, do this:
- name service: mylocalserver //not sure
- porta ragnge: ???
- local ip: //ngrok gives you a url in terminal when you start the server (I'm not sure if you can reference an IP)
- local port: newPort
- protocol: http //(ngrok gives you a different url for http and https)
You can use local tunnel
It maps your port on the localhost to a web url whithout the need to change your code

Connecting to MySQL on Node.js not initialized

I can't connect to the MySQL-database. I've googled some solutions, but none seems to work, or perhaps I haven't understood them. This is the setup:
let express = require("express");
let mysql = require("mysql");
let http = require("http");
let app = express();
http.createServer(app).listen(8000, function() {
console.log("Listening on http://localhost:" + port)
});
var connection = mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: process.env.DB_PASSWORD,
database: "users",
port: 8000
});
connection.connect();
connection.query("SELECT * FROM user", function(err, rows, fields)
{
if (err) {
console.error("error connecting: " + err.stack);
return;
}
console.log(rows[0]);
});
connection.end();
Tried to setup the connection with "socketPath" and with another port, but they both returned error:
Error: connect ECONNREFUSED 127.0.0.1:3306
at Object.exports._errnoException (util.js:1034:11)
at exports._exceptionWithHostPort (util.js:1057:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1099:14)
--------------------
at Protocol._enqueue (/vagrant/node_modules/mysql/lib/protocol/Protocol.js:141:48)
at Protocol.handshake (/vagrant/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/vagrant/node_modules/mysql/lib/Connection.js:130:18)
at Object.<anonymous> (/vagrant/app.js:12:12)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
When the connection and listen listens on same port, it doesn't return any errors, but the connection doesn't seem to initialize.
console.log(connection.connect()); // -> undefined
I'm very new to using MySQL to node so I'm probably doing this all wrong, but can't figure out what the problem is
For MAC users using MAMP
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "databasename",
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});
socketPath points to MAMP "mysql.sock" to permit the NodeJS/Mysql connection.
NOTE: the above connection also solves "Error: connect ECONNREFUSED 127.0.0.1:3306".
I hope this helps someone.
Change your connection.connect() to
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
so you can see errors.
EDIT:
Check bind-address and port in mysql config file (/etc/mysql/my.cnf). If your mysql server is running on host environment and node is running in guest (any virtualization like docker), set mysql server to listen on your local ip (eth0 like 192.168.0.x) and use same address in node config
As it turns out, I was a bit stupid. I was running the application on a Vagrant-server(virtual server), and I was trying to connect to my local-server. As soon as I tried to connect to the vagrant-server, everything worked properly. I also didn't have mysql-server properly installed to my vagrant machine.
if you don't set the port or set it to mysql default port i.e 3306 it works fine.
var connection = mysql.createConnection({
host: "127.0.0.1",
user: "mysqluser",
password: 'password',
database: "yourdatabase"
});
I don't know the exact cause(although i tried with different ports), why it's not running on different ports but here is a link that shows how to use different port number for connecting mysql.
FYI: You are setting your app to run on 8000 and again the port mysql
using in your app is 8000.You must change it to something else.
You have to set socketPath and before you run your script make sure your MAMP is running or not.
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});
Remove your port key value(port: 8000) and socketPath if you added,
from sql configuration, and try.
var connection = mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: "root",
database: "users"
});
Actually you occupied 8000 port by node server so you can't assign same port to different process.
Second mysql is running on port 3306. so you could not connect mysql through different port.
You can use different port for mysql but by some proxy pass mechanism or by running mysql itself on specific port.
Please follow simple steps to start (Worked on windows Machine):
Download and install MySQL from following link click here.
Configure downloaded file (I had kept default config parameters). Please check this video link for reference
Make sure MySQL server status is on.
Now you can check connection status by using below node code.
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
port: 3306
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL Server');
})
Start Your Mysql Server from your Xampp Control panel

Categories