【问题标题】:Issue of CORS. I already add header in serverside课程的问题。我已经在服务器端添加了标题
【发布时间】:2016-04-22 10:19:26
【问题描述】:

目前我正在创建一个在谷歌地图上显示标记的小程序。坐标来自 mysql 数据库,但我收到错误,我不知道它为什么会出现。

ERRor - XMLHttpRequest 无法加载 http://localhost:8080/markers.php。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://192.168.1.7:8100' 不允许访问。响应的 HTTP 状态代码为 404。

markers.php

<?php


  //Create a connection to the database
  $mysqli = new mysqli("localhost", "test");

    if (!$mysqli) {
        die("Connection failed: " . mysqli_connect_error());
    }
  //The default result to be output to the browser
  $result = "{'success':false}";

  //Select everything from the table containing the marker informaton
  $query = "SELECT * FROM marker";

  //Run the query
  $dbresult = $mysqli->query($query);

  //Build an array of markers from the result set
  $markers = array();

  while($row = $dbresult->fetch_array(MYSQLI_ASSOC)){

    $markers[] = array(
      'id' => $row['id'],
      'name' => $row['name'],
      'lat' => $row['lat'],
      'lng' => $row['lng']
    );
  }

  //If the query was executed successfully, create a JSON string containing the marker information
  if($dbresult){
    $result = "{'success':true, 'markers':" . json_encode($markers) . "}";        
  }
  else
  {
    $result = "{'success':false}";
  }
 //Set these headers to avoid any issues with cross origin resource sharing issues
  header('Access-Control-Allow-Origin: *');
  header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
  header('Access-Control-Allow-Headers: Content-Type,x-prototype-version,x-requested-with');

  //Output the result to the browser so that our Ionic application can see the data
  echo($result);

?>

app.js

angular.module('starter', ['ionic', 'ngCordova'])

.run(function($ionicPlatform, GoogleMaps) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }

    GoogleMaps.init();
  })
})

.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider
  .state('map', {
    url: '/',
    templateUrl: 'templates/map.html',
    controller: 'MapCtrl'
  });

  $urlRouterProvider.otherwise("/");

})

.factory('Markers', function($http) {

  var markers = [];

  return {
    getMarkers: function(){

      return $http.get("http://localhost:8080/markers.php").then(function(response){
          markers = response;
          return markers;
      });

    }
  }

})

.factory('GoogleMaps', function($cordovaGeolocation, Markers){

  var apiKey = false;
  var map = null;

  function initMap(){

    var options = {timeout: 10000, enableHighAccuracy: true};

    $cordovaGeolocation.getCurrentPosition(options).then(function(position){

      var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

      var mapOptions = {
        center: latLng,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };

      map = new google.maps.Map(document.getElementById("map"), mapOptions);

      //Wait until the map is loaded
      google.maps.event.addListenerOnce(map, 'idle', function(){

        //Load the markers
        loadMarkers();

      });

    }, function(error){
      console.log("Could not get location");

        //Load the markers
        loadMarkers();
    });

  }

  function loadMarkers(){

      //Get all of the markers from our Markers factory
      Markers.getMarkers().then(function(markers){

        console.log("Markers: ", markers);

        var records = markers.data.markers;

        for (var i = 0; i < records.length; i++) {

          var record = records[i];   
          var markerPos = new google.maps.LatLng(record.lat, record.lng);

          // Add the markerto the map
          var marker = new google.maps.Marker({
              map: map,
              animation: google.maps.Animation.DROP,
              position: markerPos
          });

          var infoWindowContent = "<h4>" + record.name + "</h4>";          

          addInfoWindow(marker, infoWindowContent, record);

        }

      }); 

  }

  function addInfoWindow(marker, message, record) {

      var infoWindow = new google.maps.InfoWindow({
          content: message
      });

      google.maps.event.addListener(marker, 'click', function () {
          infoWindow.open(map, marker);
      });

  }

  return {
    init: function(){
      initMap();
    }
  }

})

.controller('MapCtrl', function($scope, $state, $cordovaGeolocation) {

});

【问题讨论】:

    标签: php ionic-framework server


    【解决方案1】:

    Ionic 有一个配置:

    http://ionicframework.com/docs/cli/test.html

    或者如果你使用的是谷歌浏览器,你可以添加这个插件,它为我解决了问题:

    https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

    希望对你有帮助

    【讨论】:

    • thanxx ...你拯救了我的一天
    猜你喜欢
    • 1970-01-01
    • 2020-03-04
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多