Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Short tutorial on how to use Express and node-mysql
// Module dependencies
var express = require('express'),
mysql = require('mysql');
// Application initialization
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password'
});
var app = module.exports = express.createServer();
// Database setup
connection.query('CREATE DATABASE IF NOT EXISTS test', function (err) {
if (err) throw err;
connection.query('USE test', function (err) {
if (err) throw err;
connection.query('CREATE TABLE IF NOT EXISTS users('
+ 'id INT NOT NULL AUTO_INCREMENT,'
+ 'PRIMARY KEY(id),'
+ 'name VARCHAR(30)'
+ ')', function (err) {
if (err) throw err;
});
});
});
// Configuration
app.use(express.bodyParser());
// Main route sends our HTML file
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
// Update MySQL database
app.post('/users', function (req, res) {
connection.query('INSERT INTO users SET ?', req.body,
function (err, result) {
if (err) throw err;
res.send('User added to database with ID: ' + result.insertId);
}
);
});
// Begin listening
app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#user-submit').click(function () {
var payload = {
name: $('#user-name').val()
};
$.ajax({
url: "/users",
type: "POST",
contentType: "application/json",
processData: false,
data: JSON.stringify(payload),
complete: function (data) {
$('#output').html(data.responseText);
}
});
});
});
</script>
</head>
<body>
<h3>Enter a username to enter into the database:</h3>
<input id="user-name" type="text" />
<input id="user-submit" type="submit" />
<p id="output"></p>
</body>
</html>
{
"name": "reddit-node-mysql"
, "description": "A demo of how to use Express and MySQL together"
, "author": "Clarence Leung <github@clarle>"
, "version": "0.0.1"
, "private": true
, "dependencies": {
"express": "~2.5",
"mysql": "~2.0"
}
}
@vtiwarirg

This comment has been minimized.

Show comment Hide comment
@vtiwarirg

vtiwarirg Jan 23, 2014

nice demo code !

nice demo code !

@ohadperry

This comment has been minimized.

Show comment Hide comment
@ohadperry

ohadperry Feb 5, 2014

hi, question - if you would like to access 'connection' from another file, what would you do?

hi, question - if you would like to access 'connection' from another file, what would you do?

@hkabir

This comment has been minimized.

Show comment Hide comment
@hkabir

hkabir Mar 20, 2014

I got the below error when I tried to run this demo. Can you please help me to find out where is the problem?

D:\Nodejs>node app.js
Warning: express.createServer() is deprecated, express
applications no longer inherit from http.Server,
please use:

var express = require("express");
var app = express();

connect.multipart() will be removed in connect 3.0
visit https://github.com/senchalabs/connect/wiki/Connect-3.0 for alternatives
connect.limit() will be removed in connect 3.0

D:\Nodejs\app.js:55
console.log("Express server listening on port %d in %s mode", app.address().po
^
TypeError: Object function app(req, res, next){ app.handle(req, res, next); } ha
s no method 'address'
at Object. (D:\Nodejs\app.js:55:67)
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:902:3

hkabir commented Mar 20, 2014

I got the below error when I tried to run this demo. Can you please help me to find out where is the problem?

D:\Nodejs>node app.js
Warning: express.createServer() is deprecated, express
applications no longer inherit from http.Server,
please use:

var express = require("express");
var app = express();

connect.multipart() will be removed in connect 3.0
visit https://github.com/senchalabs/connect/wiki/Connect-3.0 for alternatives
connect.limit() will be removed in connect 3.0

D:\Nodejs\app.js:55
console.log("Express server listening on port %d in %s mode", app.address().po
^
TypeError: Object function app(req, res, next){ app.handle(req, res, next); } ha
s no method 'address'
at Object. (D:\Nodejs\app.js:55:67)
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:902:3

@clarle

This comment has been minimized.

Show comment Hide comment
@clarle

clarle Apr 21, 2014

Hi all, I'll be updating this gist for Express 4.0 and the latest version of node-mysql shortly. Stay tuned!

Owner

clarle commented Apr 21, 2014

Hi all, I'll be updating this gist for Express 4.0 and the latest version of node-mysql shortly. Stay tuned!

@NaturalBridge

This comment has been minimized.

Show comment Hide comment
@NaturalBridge

NaturalBridge May 4, 2014

Hey Clarence, I couldn't get this one to run (I think because of the various changes in middleware, etc... even though I'm using the suggested Express version). It looks very sweet and compact though, can't wait to see the updated one, thanks!

TypeError: Arguments to path.join must be strings
at path.js:360:15
at Array.filter (native)
at exports.join (path.js:358:36)
at exports.send (/home/user1/workspace/nodemaria/node_modules/express/node_modules/connect/lib/middleware/static.js:129:20)
at ServerResponse.res.sendfile (/home/user1/workspace/nodemaria/node_modules/express/lib/response.js:186:3)
at /home/user1/workspace/nodemaria/app.js:39:9
at callbacks (/home/user1/workspace/nodemaria/node_modules/express/lib/router/index.js:272:11)
at param (/home/user1/workspace/nodemaria/node_modules/express/lib/router/index.js:246:11)
at pass (/home/user1/workspace/nodemaria/node_modules/express/lib/router/index.js:253:5)
at Router._dispatch (/home/user1/workspace/nodemaria/node_modules/express/lib/router/index.js:280:5)

Hey Clarence, I couldn't get this one to run (I think because of the various changes in middleware, etc... even though I'm using the suggested Express version). It looks very sweet and compact though, can't wait to see the updated one, thanks!

TypeError: Arguments to path.join must be strings
at path.js:360:15
at Array.filter (native)
at exports.join (path.js:358:36)
at exports.send (/home/user1/workspace/nodemaria/node_modules/express/node_modules/connect/lib/middleware/static.js:129:20)
at ServerResponse.res.sendfile (/home/user1/workspace/nodemaria/node_modules/express/lib/response.js:186:3)
at /home/user1/workspace/nodemaria/app.js:39:9
at callbacks (/home/user1/workspace/nodemaria/node_modules/express/lib/router/index.js:272:11)
at param (/home/user1/workspace/nodemaria/node_modules/express/lib/router/index.js:246:11)
at pass (/home/user1/workspace/nodemaria/node_modules/express/lib/router/index.js:253:5)
at Router._dispatch (/home/user1/workspace/nodemaria/node_modules/express/lib/router/index.js:280:5)

@thembamalungani

This comment has been minimized.

Show comment Hide comment
@thembamalungani

thembamalungani Jul 30, 2014

Nice easy to follow demo

Nice easy to follow demo

@mikeLspohn

This comment has been minimized.

Show comment Hide comment
@mikeLspohn

mikeLspohn Aug 24, 2015

Thanks for this 👍 And ohadpartuck if you wanted to move connection into a separate file you could just place it in, say, connection.js and in that file module.exports = connection then connection = require('./connection.js') in your main app.js file.

Thanks for this 👍 And ohadpartuck if you wanted to move connection into a separate file you could just place it in, say, connection.js and in that file module.exports = connection then connection = require('./connection.js') in your main app.js file.

@seokochin

This comment has been minimized.

Show comment Hide comment
@seokochin

seokochin Oct 27, 2015

Its not working for me, So I just change

res.sendfile( '/index.html' , {root:__dirname}); //instead of res.sendfile( __dirname + '/index.html' );

Its not working for me, So I just change

res.sendfile( '/index.html' , {root:__dirname}); //instead of res.sendfile( __dirname + '/index.html' );

@stackedactors1

This comment has been minimized.

Show comment Hide comment
@stackedactors1

stackedactors1 Dec 7, 2015

How do you pass an object to the view in a regular page load? NOT an ajax call. That object (of course) came from the mysql database. I'd imagine its something like this:

app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html', {fromdb: 'list of records'});
});

let me know how to do this. thanks.

How do you pass an object to the view in a regular page load? NOT an ajax call. That object (of course) came from the mysql database. I'd imagine its something like this:

app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html', {fromdb: 'list of records'});
});

let me know how to do this. thanks.

@Hervinho

This comment has been minimized.

Show comment Hide comment
@Hervinho

Hervinho Jun 22, 2016

I get this error:
jquery.min.js:4 XMLHttpRequest cannot load file:///C:/api/users/insert. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

How do I fix it?

I get this error:
jquery.min.js:4 XMLHttpRequest cannot load file:///C:/api/users/insert. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

How do I fix it?

@sunilsinh

This comment has been minimized.

Show comment Hide comment
@sunilsinh

sunilsinh Jun 25, 2016

Thanks,
But i want to bind data from mysql to html page.

Thanks,
But i want to bind data from mysql to html page.

@kazup01

This comment has been minimized.

Show comment Hide comment
@kazup01

kazup01 Feb 11, 2017

Thanks nice demo!

kazup01 commented Feb 11, 2017

Thanks nice demo!

@dontito94

This comment has been minimized.

Show comment Hide comment
@dontito94

dontito94 Jan 25, 2018

nice demo for we bigginers

nice demo for we bigginers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment