Last active
March 19, 2016 01:32
-
-
Save marco-mendes/6b747d1e6d144eafab52 to your computer and use it in GitHub Desktop.
AloMundoNodeMySQL.js
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
// Aplicacao minima Node.JS com MySQL | |
// Carrega modulos express em mysql | |
var express = require('express'), | |
mysql = require('mysql'); | |
// Inicializa conexao com o banco de dados e servidor Web express | |
var connection = mysql.createConnection({ | |
host : 'localhost', | |
user : 'root', | |
password : 'root' | |
}); | |
var app = module.exports = express.createServer(); | |
// Configura o banco de dados | |
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; | |
}); | |
}); | |
}); | |
// Configuracao da aplicacao | |
app.use(express.bodyParser()); | |
// Requisicao / redireciona para o arquivo index.html | |
app.get('/', function(req, res) { | |
res.sendfile('index.html', { root: __dirname }); | |
}); | |
// Atualiza o banco de dados MySQL quando a rota /users for chamada. | |
// Ela é chamada como evento de submissao do formulario index.html | |
app.post('/users', function (req, res) { | |
connection.query('INSERT INTO users SET ?', req.body, | |
function (err, result) { | |
if (err) throw err; | |
res.send('Usuario adicionado ao banco de dados com ID: ' + result.insertId); | |
} | |
); | |
}); | |
// Express Ouve na porta 3000 | |
app.listen(3000); | |
console.log("Servidor express ouvindo no porto 3000", app.address().port, app.settings.env); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment