0

I'm having a difficult time posting data retrieved from a server using mysql with node. I have connected to my db successfully, and I can return the data I want by console logging it to the CLI when running "node server.js". However, I'm not sure how to post this data to my Angular view. No problem console logging, but this doesn't help me get data to the application.

For the moment, I'm just trying to get the data to index.html, which is my primary view and holds my ng-view portion for Angular routing. I'm probably missing something obvious bc I'm new to NodeJS.

// MODULES

var express = require('express');

var app = express();

var port = process.env.PORT || 3000;

var mysql = require('mysql');

var serveStatic = require('serve-static');

var bodyParser = require('body-parser');


var source = __dirname + '/public/views/index.html';

app.use(serveStatic(__dirname, {'index': ['index.html']}));

app.route('/*')
  .get(function(req, res) {

    res.sendFile(source);
  });


var data;

var connection = mysql.createConnection({
    host     : 'thehostdb',
    user     : 'username', // credentials correct, connection works
    password : 'pw',
    database : 'db',
    port: '3306'
});

connection.query('SELECT * from poemTable', function(err, rows, fields) {
    if (!err) {

        data = JSON.stringify(rows);

        setDataValue(data);

}
    else {
        console.log('Error while performing Query:', err);
    }
});

function setDataValue(value) {

    data = value;

    console.log(data); //Where the data logs
}


app.listen(port, function () {
    console.log('Example app listening on port' + port + '!')
})

1 Answer 1

0

You have to understand what this code does, and how nodejs and angular are supposed to work together. Angular is served to the client and then rendered by the clients browser. So if you want to inject data you have to fetch it. So in your angular app when the controller starts make an api call, and in your server create a new route:

app.get('/data', function(req, res, next) {
    connection.query(..., function(err, rows, fields) {
        res.json(rows);
    });
});

Make sure you understand node and it's async nature, what is event loop and how it works and what is callback hell, also I would check out promises and other tutorials on nodeschool.io, it's a great place to start with node :)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I started playing around with res.send and res.json and got the data to the view.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.