Node js with mysql rest api GETTING Error: getaddrinfo ENOENT localhost - mysql

Node js with mysql rest api GETTING Error: getaddrinfo ENOENT localhost::
In mysql phpmyadmin i have creates database named job_portal with same username and password.
webapp.js :
const express = require("express");
const app = express();
const cors = express("cors");
const dotenv = require("dotenv");
dotenv.config();
const dbService = require("./config/database");
const { response } = require("express");
//app.use(cors());
app.use(express.json());
//app.use(express.urlencoded({ extended : false }));
app.listen(process.env.app_port, () => {
//console.log("server running....", process.env);
console.log("server running on port....", process.env.app_port);
});
database.js :
const mysql = require("mysql");
const dotenv = require("dotenv");
dotenv.config();
//const { response } = require("express");
//let instance = null;
const connection = mysql.createConnection({
host : process.env.host,
user : process.env.user,
password : process.env.password,
database : process.env.database
});
console.log("process.env.db_port", process.env.user)
connection.connect((err) => {
if(err){
console.log(err);
}
console.log('db:: '+connection.state);
});
.env :
node_env = development
app_port = 5000
db_port = 3306
host = localhost
user = job_portal
password = job_portal
database = job_portal
connectionLimit = 10
Now facing error log:
process.env.db_port job_portal
server running on port.... 5000
Error: getaddrinfo ENOENT localhost
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26)
--------------------
at Protocol._enqueue (C:\xampp\htdocs\projects\job portal in jquery\webservices\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (C:\xampp\htdocs\projects\job portal in jquery\webservices\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at Connection.connect (C:\xampp\htdocs\projects\job portal in jquery\webservices\node_modules\mysql\lib\Connection.js:116:18)
at Object.<anonymous> (C:\xampp\htdocs\projects\job portal in jquery\webservices\config\database.js:14:12)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Module.require (internal/modules/cjs/loader.js:1026:19)
at require (internal/modules/cjs/helpers.js:72:18) {
errno: 'ENOENT',
code: 'ENOENT',
syscall: 'getaddrinfo',
hostname: 'localhost',
fatal: true
}
db:: disconnected
how should i fix this issue please help me to resolve

Related

Error: connect ETIMEDOUT, how to solve it? using Node.js and MySQL2

I used Node.js and MySQL2. Working on MySQL workbench. Created virtual DB using Railway workbench. Schemas and tables are created. But showing `ETIMEDOUT error in the VS code's terminal when i try to run node index.js. What can i do?
db.js:
import mysql2 from 'mysql2';
export const db = mysql2.createConnection({
host: 'containers-us-west-174.railway.app',
user: 'user',
password: 'password',
database: 'railway'
})
index.js:
import express from 'express';
import authRoutes from './routes/auth.js';
import userRoutes from './routes/users.js';
import postRoutes from './routes/posts.js';
import dotenv from 'dotenv';
import cookieParser from 'cookie-parser';
import multer from 'multer';
dotenv.config();
const app = express();
app.use(express.json());
app.use(cookieParser());
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '../client/public/upload');
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
})
const upload = multer({ storage: storage })
app.post('/api/upload', upload.single('file'), function (req, res) {
const file = req.file;
res.status(200).json(file?.filename)
});
app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/posts', postRoutes);
app.listen(8800, () => {
console.log('Connected wih backend!');
})
In my VS Code Terminal it is showing this error:
Connected wih backend!
node:events:505
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT
at Connection._handleTimeoutError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:189:17)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)
Emitted 'error' event on Connection instance at:
at Connection._notifyError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:236:12)
at Connection._handleFatalError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:167:10)
at Connection._handleNetworkError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:180:10)
at Connection._handleTimeoutError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:193:10)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7) {
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true
}
I was trying to deploting in railway. I'm using MySQL workbench.
In Railway deployment logs this error shows:
> api#1.0.0 start
> node index.js
node:internal/modules/cjs/loader:1239
return process.dlopen(module, path.toNamespacedPath(filename));
^
Error: /app/node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node: invalid ELF header
at Object.Module._extensions..node (node:internal/modules/cjs/loader:1239:18)
at Module.load (node:internal/modules/cjs/loader:1033:32)
at Function.Module._load (node:internal/modules/cjs/loader:868:12)
at Module.require (node:internal/modules/cjs/loader:1057:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/app/node_modules/bcrypt/bcrypt.js:6:16)
at Module._compile (node:internal/modules/cjs/loader:1155:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1209:10)
at Module.load (node:internal/modules/cjs/loader:1033:32)
at Function.Module._load (node:internal/modules/cjs/loader:868:12) {
code: 'ERR_DLOPEN_FAILED'
}
npm WARN config production Use `--omit=dev` instead.
And deployment crashed!
Any solution?

Node js not connected with MySQL new created database

I am trying to connect NodeJS with MySQL database.I am using WAMP. It's connected only default database like "mysql"and"information_schema" but those databases i created not connect with NodeJs and given me following error.
Please let me know where i am going wrong.
Code
**Server.js**
----------
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mysql = require("mysql");
app.use(bodyParser.json());
var connection = mysql.createConnection({
host : "localhost",
user : "root", //User Name
password : "", // No password
database : "techbiz", // Database Name
multipleStatements:true
});
connection.connect((err)=>{
if(!err)
{
console.log("Database connected ");
}
else{
console.log(err) }
})
// Initialize port
const PORT = process.env.PORT || 5000;
// send rquest to web page
app.get('/',(req,res) => res.send(`Automize Business Solution running on :${PORT}`));
app.listen(PORT,()=>console.log("Server is running"));
[Database][1]
**Error**
----------
Server is running
{ Error: ER_BAD_DB_ERROR: Unknown database 'techbiz'
at Handshake.Sequence._packetToError (K:\WebProjects\MySQL\abs-server\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Handshake.ErrorPacket (K:\WebProjects\MySQL\abs-server\node_modules\mysql\lib\protocol\sequences\Handshake.js:123:18)
at Protocol._parsePacket (K:\WebProjects\MySQL\abs-
at Socket.<anonymous> (K:\WebProjects\MySQL\abs-
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
code: 'ER_BAD_DB_ERROR',
errno: 1049,
sqlMessage: 'Unknown database \'techbiz\'',
sqlState: '42000',
fatal: true }
[1]: https://i.stack.imgur.com/E9MSc.png
Thanks
i just change my wamp version and using MySQL 5.5.8 , and now same code working fine.
thanks

connection to a remote mysql database using node

Good mornig to you guys. I want to establish a connection to a remote mysql database using node js. but i am facing this error. I do not know if I wrongly specifies the access path to the db
code
var mysql = require('mysql');
var pool = mysql.createPool({
host: "http://kamerun-it.com/mysql",
connectionLimit : 100,
database: "****",
user: "****",
password: "*****",
multipleStatements: true
});
error
throw err;
^
Error: getaddrinfo ENOTFOUND http://kamerun-it.com/mysql
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:60:26)
--------------------
at Protocol._enqueue (F:\kamerun it\aspi-api\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (F:\kamerun it\aspi-api\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at PoolConnection.connect (F:\kamerun it\aspi-api\node_modules\mysql\lib\Connection.js:119:18)
at Pool.getConnection (F:\kamerun it\aspi-api\node_modules\mysql\lib\Pool.js:48:16)
at Object. (F:\kamerun it\aspi-api\app\model\db.js:16:8)
at Module._compile (internal/modules/cjs/loader.js:956:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Module.require (internal/modules/cjs/loader.js:849:19) {
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'http://kamerun-it.com/mysql',
fatal: true
}
You probably have an error in your config with the host URL.
Here's a working example with a connection to a remote MySQL:
const mysql = require("mysql");
const connection = mysql.createPool({
host: "remotemysql.com",
user: "aKlLAqAfXH",
password: "PZKuFVGRQD",
database: "aKlLAqAfXH"
});
connection.query(
"SELECT hexcode FROM colours WHERE precedence = 2",
(err, result) => {
err ? console.log(err) : console.log(result[0].hexcode);
}
);
and here's one with mistaken host parameter:
const mysql = require("mysql");
const connection = mysql.createPool({
host: "WRONGremotemysql.com",
user: "aKlLAqAfXH",
password: "PZKuFVGRQD",
database: "aKlLAqAfXH"
});
connection.query(
"SELECT hexcode FROM colours WHERE precedence = 2",
(err, result) => {
err ? console.log(err) : console.log(result[0].hexcode);
}
);
The second one returns the same ENOTFOUND error.
Check if that's the correct URL, if the database can be accessed remotely and via which port you can use it.

ETIMEOUT error | Google Cloud SQL database with NodeJS

I have created a mysql database on google cloud that I'd like to access from a separate node web application (also running on google cloud). I am testing the connection locally on my computer first, and when I run the following code locally I can successfully establish a connection to my database and see the data in it.
'use strict';
// [START app]
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const mysql = require('mysql');
var connection = mysql.createConnection({
host : 'Cloud SQL IP',
user : 'username',
password : 'password',
database : 'db_name'
});
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// Make globals.js accessible
app.use(express.static(__dirname + '/'));
app.get('/', (req, res) => {
connection.connect();
connection.query('SELECT * FROM Users', function (error, results, fields) {
if (error) throw error;
console.log(results);
});
connection.end();
res.status(200).send('Hello World!');
});
app.get('/login', (req, res) => {
res.status(200).send();
});
// [START server]
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
// [END app]
However when run this same code in my google app engine (for both debugging on port 8080 and fully deployed on https://myapp.appspot.com) I get the following timeout error:
{ Error: connect ETIMEDOUT
at Connection._handleConnectTimeout (/home/megan_cooper2900/project/node_modules/mysql/lib/Connection.js:419:13)
at Socket.g (events.js:292:16)
at emitNone (events.js:86:13)
at Socket.emit (events.js:185:7)
at Socket._onTimeout (net.js:338:8)
at ontimeout (timers.js:386:14)
at tryOnTimeout (timers.js:250:5)
at Timer.listOnTimeout (timers.js:214:5)
--------------------
at Protocol._enqueue (/home/megan_cooper2900/project/node_modules/mysql/lib/protocol/Protocol.js:145:48)
at Protocol.handshake (/home/megan_cooper2900/project/node_modules/mysql/lib/protocol/Protocol.js:52:23)
at Connection.connect (/home/megan_cooper2900/project/node_modules/mysql/lib/Connection.js:130:18)
at app.get (/home/megan_cooper2900/journeyma/app.js:31:13)
at Layer.handle [as handle_request] (/home/megan_cooper2900/project/node_modules/express/lib/router/layer.js:95:5)
at next (/home/megan_cooper2900/project/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/megan_cooper2900/project/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/megan_cooper2900/project/node_modules/express/lib/router/layer.js:95:5)
at /home/megan_cooper2900/project/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/megan_cooper2900/project/node_modules/express/lib/router/index.js:335:12)
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true }
Why is this not working on the Google App Engine application?
In your connection configuration for mysql,host does not work on App Engine. You have to use socketPath . socketPath is the path to a unix domain socket to connect to. When used host and port are ignored. (transferred knowledge from using Loopback on App Engine flex. it had me banging my head for days lol). It's value is your Cloud SQL Instance connection name
so in your case, it should look like this: /cloudsql/my-project-12345:us-central1:mydatabase
var connection = mysql.createConnection({
socketPath : '/cloudsql/my-project-12345:us-central1:mydatabase',
user : 'username',
password : 'password',
database : 'db_name'
});
It's a similar process if you're using Postgres on GCloud which is answered here
I also did faced the same issue and I was using Kubernetes pods to access my CloudSQL instance. I got a fix by increasing the timeout in the configuration.
cloudSqlConfig: {
connectionLimit: 10,
host: 'your-host-ip',
user: process.env.DB_USERNAME,
password: process.env.DB_PASSKEY,
database: 'myDB',
connectTimeout: 20000,
waitForConnections: true,
queueLimit: 0
},

Error when connecting to MYSQL Database (NodeJS, socket.io, express)

me and a friend just started to work on a little App. It uses NodeJS (with Socket.io and Express). We're kind of new into NodeJS and thus can't really comprehend why we get the error we get. Every inch of help is appreciated :)
Here's the code:
var express = require('express');
var app = express();
var serv = require('http').Server(app);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client', express.static(__dirname + '/client'));
serv.listen(2000);
console.log("Server started!");
var io = require('socket.io')(serv,{});
var md5 = require('md5');
var mysql = require('mysql');
var dbconn = mysql.createConnection({
host: "mySERVER",
user: "myUSER",
password: "myPASSWORD",
database: "myDBNAME"
});
dbconn.connect(function(err) {
if (err) throw err; //THE ERROR IS THROWN HERE
});
io.sockets.on("connection", function(socket) {
socket.on("register", function(obj){
var sql = 'INSERT INTO users (name, password) VALUES ("' + obj.name + '", "' + md5(obj.password) + '")';
dbconn.query(sql, function (err, result) {
if (err) throw err;
console.log("Result: " + result);
});
});
});
And here's the Error Message:
Error: connect ECONNREFUSED mySERVER:3306
at Object.exports._errnoException (util.js:1018:11)
at exports._exceptionWithHostPort (util.js:1041:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1086:14)
--------------------
at Protocol._enqueue (PROJECTPATH\node_modules\mysql\lib\protocol\Protocol.js:145:48)
at Protocol.handshake (PROJECTPATH\node_modules\mysql\lib\protocol\Protocol.js:52:23)
at Connection.connect (PROJECTPATH\node_modules\mysql\lib\Connection.js:130:18)
at Object.<anonymous> (PROJECTPATH\app.js:32:8)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
Thank you in advance!
It's a database connection error. You're mysql host and/or port are wrong.
Make sure the information passed to the mysq.createConnection function in the code below are correct:
var dbconn = mysql.createConnection({
host: "mySERVER",
user: "myUSER",
password: "myPASSWORD",
database: "myDBNAME"
});