Skip to content

Instantly share code, notes, and snippets.

@Abiwax
Created Oct 4, 2017
Embed
What would you like to do?
Node MySQL connection
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