iJamesPHP iJamesPHP - 3 months ago 14
AngularJS Question

Data-binding using Node and Angular

I've been following this tutorial for data-binding using Node and Angular: https://codeforgeek.com/2014/09/two-way-data-binding-angularjs/

Here's my server code:

var express = require("express");
var mysql = require("mysql");
var app = express();
/*
* Configure MySQL parameters.
*/
var connection = mysql.createConnection({
host : "localhost",
user : "root",
password : "password",
database : "csflip"
});

/*Connecting to Database*/
var log = console.log;


jamesBug = function(txt) {
var d1 = new Date();

var logtxt = "["+d1.toUTCString()+"] "+txt;
console.log(logtxt);

}
connection.connect(function(error){
if(error)
{
jamesBug("Problem with MySQL"+error);
}
else
{
jamesBug("Connected with Database");
}
});

/*Start the Server*/

app.listen(3000,function(){
jamesBug("It's Started on PORT 3000");
});


app.get('/',function(req,res){
res.sendfile('index.php');
});

app.get('/loadcoinflips',function(req,res){
jamesBug("Got a load request for conflip listings from database.")
connection.query("SELECT * FROM coinflips WHERE accepted = '0'",function(err,rows){
if(err)
{
jamesBug("Problem with MySQL: "+err);
}
else
{
jamesBug("Recieved the data from the database.");
jamesBug("Data recieved stringified to JSON: ("+JSON.stringify(rows)+")");

res.end(JSON.stringify(rows));

jamesBug("Outputted the JSON data.");
}
});
});


This is my core.js file:

app.controller('two_way_control',function($scope,$http,$interval){
load_pictures();
$interval(function(){
load_pictures();
},300);
function load_pictures(){
$http.get('http://localhost:3000/loadcoinflips').success(function(data){
$scope.ids=data;
});
};
});


This is how I'm displaying the data:

<div id="container" ng-app='two_way' ng-controller='two_way_control'>
<div class="row" ng-repeat="data in ids">
<h2>{{data.id}}</h2>
<br />
</div>
</div>


However, when I load my page It's blank, am I being stupid or can somebody help me out...

Thanks,

James

Answer

Try using this:

app.all('/*', function(req, res, next) {
  // CORS headers
  res.header("Access-Control-Allow-Origin", "*");
  // restrict it to the required domain
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  // Set custom headers for CORS
  res.header('Access-Control-Allow-Headers', 'Authorization,Content-type,Accept,X-Access-Token,X-Key');
  if (req.method === 'OPTIONS') {
    res.status(200).end();
  } else {
    next();
  }
});
Comments