I'm trying to connect to my local mysql database by using node.js on my website. I have installed node.js on my laptop. This is my code that is executed:
function registerUser()
{
var mysql = require("mysql");
var connection = mysql.createConnection( {
host: 'localhost',
user: 'root',
password: '',
database: 'Fountaint_News_Database',
port: 3306
});
connection.connect();
var query = connection.query('INSERT INTO registered_users VALUES ("test", 22)',
function(err, result, fields) {
if (err) throw err;
console.log('result: ', result);
});
connection.end();
console.log('Connection closed');
}
I haven't done anything else, I'm not sure if there is anything else to setup, but when I runt I just get this error "ReferenceError: Can't find variable: require".
I hope that someone can help me.
Are you running this code on the server side, not on the client don't you? I mean saving this file on a .js file, running via console via
node yourfile.js
after obviously a
npm install mysql
in the same directory?
Obviously you need to bind the registerUser() function to some event :)
Related
Hello Stacksoverflowers,
I have a problem to connect my server.js file to Mysql via Express.
I've already insatlled mysql and express via npm.
when i run my server.js
The only thing it says in my console (MacOS default terminal) is:
"node server running now - using http://localhost:3000"
(I got no errors)
and my webpage also showing correct - "Node Server running - startpage" in the browser.
The problem is that they say nothing like "Connected to the MySQL server" or "Timeout: error messages" ?? (look at #3)
// Dan k
//#1
// My codes from server.js
const express = require('express');
const mysql = require('mysql');
const hostname = "localhost:";
const port = 3000;
//#2
// create connection to DB
const connection = mysql.createConnection({
host: "localhost",
user: 'root',
password: 'root',
port: 3000
});
//#3
// Connect to DB
connection.connect(function(err) {
if (!err) {
console.log('Connected to the MySQL server.');
}
else if (err)
{
return console.error('Timeout: ' + err.message);
}
});
// Routing with Express
const app = express();
//#4
// Startpage (root)
app.get('/', function(request, response){
response.send('Node Server running - startpage...');
response.end();
})
connection.end();
//#5
app.listen(port, (err) => {
if(err) throw err;
console.log("node server running now - using http://"+(hostname)+ .
(port)");
});
I got what is causing the issue. You are using the same port number 3000 to connect to your mysqlDB and at the same time using the same port to run your nodejs application.
This does throw an error but it takes a really long time to throw the error.
So the simple answer here is that the port that you are mentioning in your createConnection() method is incorrect and needs to be changed. This port should be port number on which your mysql DB is running. From the error it is clear that your mysql DB is not running on port 3306. You can check this post to figure out which port is your mysql DB running on. https://serverfault.com/questions/116100/how-to-check-what-port-mysql-is-running-on. Below is a reference for you. Please see the comments.
// create connection to DB
const connection = mysql.createConnection({
host: "localhost",
user: 'root',
password: 'root',
port: 3000 // You need to change this and put in the correct port number.
});
I am looking for a sample and how to make ajax call to get data from MySQL for Nodejs/Express projects.
I have database connection established in app.js file. That's starts when node is running. This is db.js file.
const mysql = require('mysql');
let db_connected =false;
const ut_mysql_con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'pass',
database: "db"
});
mysql_con.connect(function(err) {
if (err) throw err;
else {
console.log("Connected!");
db_connected = true;
}
});
module.exports = mysql_con;
module.exports.db_connected = db_connected;
I also have an ejs file for front end from which ajax call is made.
<script>
$(document).ready(()=>{
//this where actual call would go if i knew how to do it.
});
</script>
I am comfortable with writing actually queries, but can't find a way of properly using ajax.
Thanks in advance for any guidance.
I recently started learning Nodejs to connect to MySQL and i'm having connection issues. I tried using putty to connect and i'm able to do so without any issues
this is my example.route.js file
const express = require('express'),
router = express.Router(),
mysql = require('mysql');
var connection = mysql.createConnection({
host: <ipaddress>,
port: <default Port>,
user: 'root',
password: <given password>,
database: <db name>,
connectionTimeout: 30000
});
connection.connect((error) => {
if (error) {
console.log('error connecting: ' + error);
} else {
console.log('Connected to server');
}
});
connection.query('SELECT * FROM test', function(err, results, fields) {
console.log('results in table: ' + results);
console.log('fields in table: ' + fields); // -1
connection.release();
if (err) throw error;
});
connection.end();
module.exports = router;
i get the following error => Error: connect ECONNREFUSED (Will update with complete error in a few hours)
As i mentioned before i used PUTTY in order to make sure there was an issue when connecting but i was able to connect to the given database name, host with the same user and password.
Not sure if this helps is an ubuntu server with MySQL
Anyone has an idea of why i'm getting the connection error? I would appreciate it the help
I'm trying to connect to my local MySql server from node.js/express application using mssql with following config:
// Database connection
var sql = require('mssql');
var config = {
user: 'db_user',
password: 'db_pass',
server: 'localhost',
database: 'project_db'
};
sql.connect(config, function (err) {
if (err) {
console.log(err);
}
});
I get this error:
{ [ConnectionError: Failed to connect to localhost:1433 - connect ECONNREFUSED 127.0.0.1:1433]
name: 'ConnectionError',
message: 'Failed to connect to localhost:1433 - connect ECONNREFUSED 127.0.0.1:1433',
code: 'ESOCKET' }
I know I have to enable TCP/IP connections for my local MySql server, but I can not find how to do it on OSX El Capitan. There is nothing like control panel with settings. That's all available at System Preferences > MySql:
Any ideas how to fix this, guys? Thanks for trying to help.
mssql and mysql are two very different things... You should use the node-mysql or some other mysql client library if you are going to be running mysql on your dev machine
https://github.com/felixge/node-mysql
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
I want to have a server running to make some entries in a database. I havent done that before. Im using node.js, express for the server and mysql with node-mysql and host it on uberspace as a low-cost webhosting service. When im starting the server with 'nohup node app.js &' everything seems to work fine, but after some time, I dont get any response from the server in a webbrowser anymore. I think the server just hang up and I want to restart it automatically. Here the simple code for my app.js:
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '***',
database: '***',
user : '***',
password: '***',
port: 3306
});
connection.connect(function(err) {
console.log(err);
});
app.get('/test', function(req,res) {
var post = {ID: 1, User: "testuser"};
var query = connection.query('INSERT INTO testtabelle123 SET ?', post, function(err, results){
console.log(err);
});
console.log(query.sql);
res.send(query.sql);
});
I guess I simply just have to make a little change for automatically restart in the code and maybe use some sort of middleware/tool for that. Can you tell me what to do? Havent found simple solutions on SO so far.
Problem occurs because mysql is closing connection when there is no connection (after sometime). Add this to make connection alive forever:
setInterval(function () {
connection.query('SELECT 1', [], function () {})
}, 5000)
Relevant issue: https://github.com/felixge/node-mysql/issues/1337