请求的资源上不存在“Access-Control-Allow-Origin”标头。 - 离子

时间:2015-05-17 02:48:38

标签: ionic

我正在尝试在我的离子应用程序上设置HTTP-get请求,但我一直收到此错误:

XMLHttpRequest cannot load http://www.wikicode.co.uk/announcement?
date=value2&message=value3&name=value1. No 'Access-Control-Allow-Origin' 
header is present on the requested resource. Origin 'http://localhost:8100'     
is therefore not allowed access.

我不确定是什么问题。我试过谷歌搜索但没有太多运气。

这是我的代码:

html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title>Announcement</title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
    <script src="js/controllers.js"></script>
    <script src="js/services.js"></script>
  </head>
  <body ng-app="Announcement">
    <ion-view view-title="Announcements">
      <ion-pane>
        <ion-header-bar class="bar-stable">
          <h1 class="title">Announcement</h1>
        </ion-header-bar>
         <br>
         <br>
         <br>
        <ionic-content ng-controller="Controller">
          <button class="button" ng-click="getData()">Do something</button>
          <br>
         name: {{name}} {{date}} {{message}}
          </ionic-content>
      </ion-pane>
    </ion-view>
  </body>
</html>

Javascript:

angular.module('starter.controllers', [])

.controller('announcementsCtrl', function($scope) {})

.controller('chatsCtrl', function($scope) {})

.controller('photosCtrl', function($scope) {})

.controller('profilesCtrl', function($scope) {})

.controller('Controller', function($scope, $http) {

    $scope.getData = function() {
        $http.get("http://www.wikicode.co.uk/announcement", { params: { "name": "value1", "date": "value2", "message": "value3"} })
            .success(function(data) {
                $scope.name = data.name;
                $scope.date = data.date;
                $scope.message = data.message;
            })
            .error(function(data) {
                alert("ERROR");
            });
    }

});

1 个答案:

答案 0 :(得分:1)

这是RESTful API的常见问题,它不支持CORS标头。您可以使用Ionic CLI中的代理选项在开发期间解决此问题。我在我的网站http://ionicinaction.com/blog/how-to-fix-cors-issues-revisited/上写了一篇关于此的教程。

要记住的重要一点是,这仅适用于构建应用程序。它没有解决问题的根源。您有两个选择:1)获取wikicode.co.uk以支持CORS标头或2)创建另一个代理真实API但又添加CORS标头的REST API。有很多方法可以做#2,但这里是如何构建一个简单的节点服务器来做到这一点。 http://chafey.blogspot.com/2014/09/working-around-cors.html