Reputation: 115
I am trying to have angular grab data from mysql through the nodejs server and I cannot seem to get it to work. When i go to postman it shows me the data when i enter http://localhost:8080/locations.
{
"status": "200",
"items": [
{
"city": "New York",
"state": "NY",
"desc": "Google NYC",
"lat": 40.7418,
"long": -74.0045
}
]
}
When I check the console it gives me this error."Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/locations. (Reason: CORS header 'Access-Control-Allow-Origin' missing)."
I am trying to use an $http.get to get the data that is in the mysql. Nodejs connects successfully to mysql. Should i be using a different method I am very new to angular and nodejs and thought this would be a fun project to try.
Any help is greatly appreicated
angular.js
//Angular App Module and Controller
var sampleApp = angular.module('mapsApp', []);
sampleApp.controller('MapCtrl', function ($scope, $http) {
var cities = $http.get('http://localhost:8080/locations').success(function (data){
$scope.items = data;
})
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(41.5, -73),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
$scope.markers = [];
var infoWindow = new google.maps.InfoWindow();
var createMarker = function (info) {
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(info.lat, info.long),
title: info.city
});
marker.content = '<div class="infoWindowContent">' + info.desc + '</div>';
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent('<h2>' + marker.title + '</h2>' + marker.content);
infoWindow.open($scope.map, marker);
});
$scope.markers.push(marker);
}
for (i = 0; i < cities.length; i++) {
createMarker(cities[i]);
}
$scope.openInfoWindow = function (e, selectedMarker) {
e.preventDefault();
google.maps.event.trigger(selectedMarker, 'click');
}
});
googleMaps.html
<!DOCTYPE html>
<html ng-app="mapsApp">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" href="css/maps.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"> </script>
<script
src="http://maps.googleapis.com/maps/api/js?sensor=false&language=en"></script>
<script type="text/javascript" src="js/maps.js"></script>
</head>
<body>
<div ng-controller="MapCtrl">
<div id="map"></div>
<div id="repeat" ng-repeat="marker in markers | orderBy : 'title'">
<a id="country_container" href="#" ng-click="openInfoWindow($event, marker)">
<label id="names" >{{marker.title}}</label></a>
</div>
<ul>
<li ng-repeat="item in items">
{{item}}
</li>
</ul>
</div>
</body>
</html>
app.js
//Rest HTTP stuff
var express = require('express');
var bodyParser = require('body-parser');
var dbGoogle = require('./dbGoogle');
var app = express();
// configure body parser
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// create our router
var router = express.Router();
// middleware to use for all requests
router.use(function (req, res, next) {
// do logging
console.log('Incoming request..');
next();
});
// test route to make sure everything is working
router.get('/', function (req, res) {
res.json({message: 'Welcome!'});
});
router.route('/locations')
// get all the locations
.get(function (req, res) {
dbGoogle.getGoogles(function (err, data) {
if (data) {
res.json({
status: '200',
items: data
});
} else {
res.json(404, {status: err});
}
});
})
// Register routes
app.use('', router);
// START THE SERVER
app.listen(port);
console.log('Running on port ' + port);
db.js
var mysql = require('mysql');
var app = require('./app.js');
var pool = mysql.createPool ({
host: 'localhost',
user: 'root',
port: 3306,
password: 'password',
database: 'testdb'
});
module.exports.pool = pool;
pool.getConnection(function(err){
if(!err) {
console.log("Database is connected\n\n");
} else {
console.log(err);
}
});
dbGoogle.js
var db = require('./db.js');
var getGoogles = function getGoogles(callback) {
db.pool.getConnection(function (err, connection) {
// Use the connection
connection.query('SELECT * FROM locations', function(err, results){
if (!err) {
if (results != null) {
callback(null, results);
} else {
callback(err, null);
}
} else {
callback(err, null);
}
//release
connection.release();
});
});
}
module.exports.getGoogles = getGoogles;
Upvotes: 0
Views: 975
Reputation: 748
Your issue isn't related to node, express, or angular. It looks like you aren't serving any static files from within your node application, but instead simply loading your index.html from the file system. Modern browsers won't allow you to make AJAX requests (even to localhost) from pages that you load from the file:// protocol.
First, add a static file handler to your express app (http://expressjs.com/en/starter/static-files.html):
app.js
...
// Register routes
app.use('', router);
// Serve static content files
app.use(express.static('relative/path/to/your/html'));
// START THE SERVER
app.listen(port);
...
Then open http://localhost:8080/index.html in your browser instead of the file:// url, your ajax request should work now.
Additionally, you could modify the angular.js
file to use a relative url:
angular.js
...
var cities = $http.get('/locations').success(function (data){
$scope.items = data;
})
...
Upvotes: 1