javascript - Angular http.get 未从 mysql nodejs 接收数据

标签 javascript mysql angularjs node.js

我试图通过nodejs服务器从mysql Angular 抓取数据,但我似乎无法让它工作。当我去 postman 时,它会显示我输入 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 header “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;

最佳答案

您的问题与 Node 、Express 或 Angular 无关。看起来您没有从 Node 应用程序中提供任何静态文件,而是简单地从文件系统加载 index.html 。现代浏览器不允许您从通过 file://协议(protocol)加载的页面发出 AJAX 请求(甚至向本地主机发出请求)。

首先,向您的 Express 应用添加静态文件处理程序 ( 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在您的浏览器中而不是 file://url 中,您的 ajax 请求现在应该可以工作了。

此外,您可以修改 angular.js 文件以使用相对 URL:

Angular.js

...
var cities = $http.get('/locations').success(function (data){
    $scope.items = data;
})
...

关于javascript - Angular http.get 未从 mysql nodejs 接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34253773/

相关文章:

javascript - 两个数组的智能合并(3-way-kindof)

javascript - FF扩展名: saving a value in preferences and retrieving in the js file

php - 相关问题算法

AngularJS v1.0.0 指令在 v1.0.7 中不起作用

javascript - 为什么这里的仪表板状态没有被 $state.go ('dashboard' ... 命中?

javascript - 如何在点击选项卡内容时获取文本框

javascript - Redux 表单不受应用程序管理,出现奇怪的错误

mysql - 比较mysql中的2列

php - SQL/PHP - 在两个日期之间选择,并打印日期

jquery - 打开和关闭容器 (div)