Saturday 8 April 2017

angular + node(express) + mysql

How to use all these together? For example, I have a simple database with one table (ID, text, done) and a code to export data from mySQL to JSON file. JSON file looks like:

[{ "id":"1", "text":"learn angular", "done":true },
 { "id":"2", "text":"build an angular app", "done":false}]

And the server.js file:

var fs = require('fs');
var serverUrl = 'localhost';
var port = 3000;
var path = require('path');
var express = require('express');
var app = express();
var http = require('http').Server(app);
var mysql = require('mysql');
var bodyParser     = require('body-parser');
var methodOverride = require('method-override');
app.use(bodyParser.json()); // parse application/json 
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); 
app.use(bodyParser.urlencoded({ extended: true })); 
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(express.static(__dirname + '/public'));
require('./app/routes')(app); // pass our application into our routes
app.get('/', function(req, res){
res.sendfile('public/index.html');
});

var connection = mysql.createConnection({
    host : 'localhost',
    user : 'root',
    password : '',
    database : 'todos',
});

connection.connect();

app.get('/',function(request,response){
connection.query('SELECT * FROM todos', function(err, rows, fields, res)

{
        console.log('Connection result error '+err);
        console.log('no of records is '+rows.length);
        response.writeHead(200, { 'Content-Type': 'application/json'});
        response.end(JSON.stringify(rows));
        });

app.set('port', 3000);

http.listen(port, function(){
console.log('listening on: ' + app.get('port'));
});

exports = module.exports = app;

What should I do next? How can I use exported from mysql to JSON data in angularjs app? The index.html file:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<base href="/">

<title></title>

<!-- CSS -->

<!-- JS -->

<!-- ANGULAR CUSTOM -->
</head>

<body ng-app="App" ng-controller="Controller">
<div class="someClass">
<table>
<tr>
    <th>id</th>
    <th>text</th>
    <th>done</th>
</tr>
<tr ng-repeat="todo in todos">
    <td></td>
    <td></td>
    <td></td>
</tr>
</table>
<div>
</body>
</html>

Do I understand correct the whole mechanism of this? We have some DB in mysql, convert mysql data into json objects and then read these objects with angular? If that's so, than how can we perform crud operations with database? Thanks in advance for any advice and answer that will help me to understand it.



via Kirill

No comments:

Post a Comment