Created
October 4, 2017 23:52
-
-
Save Abiwax/ec8fc89ed35d569364c7fb3c24f3f13e to your computer and use it in GitHub Desktop.
Node MySQL connection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mysql = require('mysql'); | |
var express = require('express'); | |
var app = express(); | |
var connection = mysql.createConnection({ | |
host : "localhost", | |
user : "username", | |
password: "yourpassword", | |
database: "Example" | |
}); | |
connection.connect(function(err) { | |
if (err) throw err; | |
console.log("Connected!"); | |
}); | |
var queryString = 'SELECT * FROM test'; | |
// Fetching data from database | |
app.get('/', function(req, res) { | |
connection.query(queryString, function (err, rows, fields) { | |
if (err) { | |
throw err; | |
} | |
return res.json(rows); | |
}); | |
// connection.end(); | |
}); | |
//enable cross-domain request. | |
var allowCrossDomain = function(req, res, next) { | |
res.header('Access-Control-Allow-Origin', '*'); | |
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); | |
res.header('Access-Control-Allow-Headers', 'Content-Type'); | |
next(); | |
}; | |
app.use(allowCrossDomain); | |
app.listen(3000, function() { | |
console.log("Server listening on port 3000"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment