What is causing MySQL Database to refuse connection? - javascript

I am trying to use MySQL for a local database in my Electron app to store settings and user data but am getting the following error:
Error: connect ECONNREFUSED 127.0.0.1:3306
I can't seem to figure out what is causing this and think I have it properly set up. Here is the code for my setup:
// main.js (Electron's main file)
const path = require('path');
require(path.resolve(`${__dirname}/assets/server/server`));
// server.js
const express = require('express');
const apiRouter = require('./routes/index');
const app = express();
app.use(express.json());
app.use('/api', apiRouter);
app.listen('3000', error => {
if (error) {
return console.error(error);
}
console.log('Server started on Port: 3000');
});
// routes - index.js
const express = require('express');
const db = require('../db/index');
const router = express.Router();
router.get('/', async (request, response, next) => {
try {
response.json(await db.all());
} catch (error) {
console.error(error);
response.sendStatus(500);
}
});
module.exports = router;
// db - index.js
const mysql = require('mysql');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: null,
database: 'storage',
connectionLimit: 10,
port: 3306
});
function all () {
return new Promise((resolve, reject) => {
pool.query('SELECT * FROM Products', (error, results) => {
if (error) {
return reject(error);
}
resolve(results);
});
}).catch((error) => {
console.error(error);
});
}
module.exports = { all };

Related

Connecting to MySQL Database from React?

I've been having problems with connecting to a database. It is a remote database and no matter what I do, it just doesn't work! I've searched all around to no avail. I'm using React for doing so. I just want to make a simple connection and be able to run some queries. Here's the code:
db.js component:
const mysql = require('mysql');
const db = mysql.createConnection({
/*THE VALUES BELOW ARE NOT THE ONES I HAVE TO USE*/
host: '11.111.11.11',
user: 'username',
password: 'password',
port: 'port',
database: 'database'
});
module.exports = db;
server.js in my backend folder:
const express = require('express');
const db = require('./config/db');
const cors = require('cors');
const app = express();
const PORT = 3002;
app.use(cors());
app.use(express.json());
//ROUTE
app.get("/db", (req, res) => {
db.query("SELECT * FROM users", (err, result) => {
if(err) {
console.log(err);
} else {
res.send(result);
console.log(result);
console.log('Connected!');
}
});
});
app.listen(PORT, ()=>{
console.log(`Server is running on http://localhost/${PORT}/`);
});
I'm not getting anything from it, not even the logged info I asked for in the console.log()
Thanks for the help, in advance.
You have just created the connection, however you need also use the connect function to connect to your database. So you need to add a line in your server.js, (I have put a comment near the line that you missed to write.
const db = require('./config/db');
const cors = require('cors');
const app = express();
const PORT = 3002;
app.use(cors());
app.use(express.json());
db.connect(); // you missed this line
//ROUTE
app.get("/db", (req, res) => {
db.query("SELECT * FROM users", (err, result) => {
if(err) {
console.log(err);
} else {
res.send(result);
console.log(result);
console.log('Connected!');
}
});
});
app.listen(PORT, ()=>{
console.log(`Server is running on http://localhost/${PORT}/`);
});
I think you can also do this in db.js before exporting db.

mvc pattern in hapi.js

i'm trying to orgnize the a hapi folder i added the database also the route but i cant seem to find a way to add the controller , so how i can make it so i can use controller instead of adding all the code in the router
thank you so much
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: ""
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
module.exports = con
Routes
"use strict";
const Path = require("path");
module.exports = [
{
method: 'GET',
path: '/',
handler: (request, h) => {
return 'Hello World!';
}
}
];
main.js
'use strict';
const Hapi = require('#hapi/hapi');
const Routes = require("./lib/routes");
const db = require('./config/db')
const init = async () => {
const server = Hapi.server({
port: 3000,
host: 'localhost'
});
server.route(Routes);
await server.start();
console.log('Server running on %s', server.info.uri);
};
db.connect
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();

The content-type is not JSON compatible

With the following code Im trying to create a accessToken with the simple-oauth2 library in node.
I have the server.js and the app.js files. The problem is that every time I try to call the getToken method it returns the following error The content-type is not JSON compatible. Im calling the /token endpoint with postman where the request´s Content-Type is set to application/json.
Has anyone encountered this problem before?
server.js
'use strict';
const app = require('express')()
const bodyParser = require('body-parser')
app.use(bodyParser.json())
const port = 3000;
module.exports = (cb) => {
app.listen(port, (err) => {
if (err) return console.error(err);
console.log(`Express server listening at http://localhost:${port}`);
return cb({
app
});
});
};
app.js
const createApplication = require('./server');
const simpleOauthModule = require('simple-oauth2');
require('dotenv').config()
const credentials = {
client: {
id: process.env.CLIENT_ID,
secret: process.env.CLIENT_SECRET
},
auth: {
tokenHost: 'http://localhost:3000/test'
}
};
createApplication(({ app }) => {
app.post('/token', async (req, res) => {
const oauth2 = simpleOauthModule.create(credentials);
var contype = req.headers['content-type']; // <-- application/json
const tokenConfig = {
username: "test",
password: "1234"
};
try {
const result = await oauth2.ownerPassword.getToken(tokenConfig); //Error occuress
const accessToken = oauth2.accessToken.create(result);
console.log('Access Token: ', accessToken);
} catch (error) {
console.log('Access Token Error', error.message);
}
});
app.post('/test', async (req, res) => {
});
});

Redirect after Post method , expressjs

I'm learing ExpressJS, and so far I did the user registration part but when I want to redirect to the home page after finishing the registration, it's not
showing the json after clicking on Submit button. May I know how I could do it.
Database
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database:'reciepeapp'
});
module.exports = con
the ORM
const con = require('./db')
The ORM
const orm = {
insertOne: function (values, cb) {
const sqlQuery = "INSERT INTO authentication(username,password) VALUES ?";
con.query(sqlQuery, [values],function (err, data) {
if (err) {
console.log(err)
cb(err, null);
} else {
cb(null, data);
}
});
},
}
module.exports = orm;
The route.js
Here I insert the data obtained during registration (register index html) into a database. It's working well but I want to redirect to home page.
const express = require('express');
const app = express()
const router = express.Router()
const bcrypt = require('bcrypt');
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
const orm = require('../models/orm')
router.get('/',(req,res)=>
res.render('home')
)
router.get('/login',(req,res)=>
res.render('login')
)
router.get('/register',(req,res)=>
res.render('register')
)
router.post("/register", async (req, res) =>{
try {
const hashedPassword = await bcrypt.hash(req.body.password,10)
values = { username: req.body.name,
password:hashedPassword }
orm.insertOne(values, function(error) {
if (error) {
return res.status(401).json({
message: 'Not able to add'
});
}
values = { username: values.username,
password: values.password }
orm.insertOne(values, function(error) {
if (error) {
return res.status(401).json({
message: 'Not able to add'
});
}
**return res.send({
username: values.username,
password: values.password
});**
});
});
}
catch {
}
});
module.exports = router
const express = require('express');
const app = express()
const bodyParser = require("body-parser");
const indexRouter = require('./routes/route')
const con = require('./models/db')
con.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var exphbs = require('express-handlebars');
console.log(__dirname)
app.use('/',express.static(__dirname + '/public'));
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.use('/',indexRouter)
const PORT = 5000;
app.listen(PORT,()=>console.log('it started on 5000'))
To do this you need to use express's redirect method.
Example:
var express = require('express');
var app = express();
const urlBase = 'localhost:3000/'
app.post('/', function(req, res) {
const redirectUrl = "index.html"
res.redirect(urlBase + redirectUrl);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
Docs: Express 4.x Docs

Reusing postgresql pool in other node javascript files

I am creating nodejs backend app with postgresql database. What I want is when once I create connection to database in my db.js file, that I can reuse it in other files to execute queries.
This is my db.js file
const pool = new Pool({
user: 'us',
host: 'localhost',
database: 'db',
password: 'pass',
port: 5432,
})
pool.on('connect', () => {
console.log('connected to the Database');
});
module.exports = () => { return pool; }
And this is how I tried to use it in index.js file
const db = require('./db.js')
app.get('/', (request, response) => {
db().query('SELECT * FROM country'), (error, results) => {
if (error) {
response.send(error)
}
console.log(results)
response.status(201).send(results)
}
})
There aren't any errors, and when I go to this specific page, it's keep loading. Nothing in console also.
But, if I write a function in my db.js file and do something like pool.query(...), export it, and in my index.js I write app.get('/', exportedFunction), everything is working fine.
Is there any way not to write all my (like 50) queries in just one (db.js) file, because I want to organise my project a little bit?
To streamline your project structure entirely, if you're starting from scratch maybe try this :
index.js
const express = require('express');
const app = express();
const PORT = 8080;
const bodyparser = require('body-parser');
const baseRouter = require('../your-router');
app.use(bodyparser.json());
app.use(express.json());
app.use('/', baseRouter);
app.listen(PORT, function () {
console.log('Server is running on PORT:', PORT);
});
your-router.js
const Router = require('express');
const router = Router();
const getCountries = require('../handlers/get');
router.get('/check-live', (req, res) => res.sendStatus(200));
// route for getCountries
router.get('/countries', getCountries);
src/handler/get.js
const YourService = require('./service/your-service');
function getCountries(request, response) {
const yourService = new YourService();
yourService.getCountries(request)
.then((res) => { response.send(res); })
.catch((error) => { response.status(400).send({ message: error.message }) })
}
module.exports = getCountries;
src/service/your-service.js
const connectionPool = require('../util/dbConnect');
class yourService {
getCountries(req) {
return new Promise(((resolve, reject) => {
connectionPool.connect((err, db) => {
if (err) reject(err);
let query = format('SELECT * FROM country'); // get inputs from req
db.query(query, (err, result) => {
if (err) reject(err);
resolve(result);
})
});
}));
}
}
module.exports = yourService;
dbConnect.js
const pgCon = require('pg')
const PGUSER = 'USER'
const PGDATABASE = 'localhost'
let config = {
user: PGUSER,
database: PGDATABASE,
max: 10,
idleTimeoutMillis: 30000
}
let connectionPool = new pgCon.Pool(config);
module.exports = connectionPool;
Please consider this as a basic example, refactor your code to use callbacks/async awaits (in the above example you can just use callbacks not needed to convert into promise), if needed - you can have DB-layer calls from the service layer in order to extract DB methods from the service layer.

Categories

Resources