我试图通过nodejs服务器从mysql获取角度抓取数据,我似乎无法让它工作。当我去邮递员时,它会在我输入http://localhost:8080/locations时向我显示数据。
{
"status": "200",
"items": [
{
"city": "New York",
"state": "NY",
"desc": "Google NYC",
"lat": 40.7418,
"long": -74.0045
}
]
}
当我检查控制台时,它会给我这个错误。"跨源请求被阻止:同源策略不允许在http://localhost:8080/locations读取远程资源。 (原因:CORS标题' Access-Control-Allow-Origin'缺失)。"
我正在尝试使用$ http.get来获取mysql中的数据。 Nodejs成功连接到mysql。如果我使用不同的方法,我对angular和nodejs很新,并认为这将是一个有趣的项目尝试。
任何帮助都非常有用
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;
答案 0 :(得分:1)
您的问题与node,express或angular无关。看起来您没有在节点应用程序中提供任何静态文件,而只是从文件系统中加载index.html。现代浏览器不允许您从从file:// protocol加载的页面发出AJAX请求(甚至是localhost)。
首先,将静态文件处理程序添加到您的快速应用程序(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);
...
然后在您的浏览器中打开http://localhost:8080/index.html而不是文件:// url,您的ajax请求现在应该可以使用。
此外,您可以修改angular.js
文件以使用相对网址:
<强> angular.js 强>
...
var cities = $http.get('/locations').success(function (data){
$scope.items = data;
})
...