Ionic应用程序和服务器帖子:访问控制允许来源

Ionic App and server post: Acces-Control-Allow-Origin

本文关键字:访问控制 应用程序 服务器 Ionic      更新时间:2023-09-26

我对angularJs很陌生,在我的ionic应用程序中,我试图向我的服务器发送一个json,这是控制器:

`enter code here`.controller('DashCtrl', ['$scope','$http',function($scope, $http) {
    $scope.formData = {};
    $scope.sendForm = function(){
         
        $http({
        method  : 'POST',
        url     : 'http://www.---.org/appForm.php',
        data    : JSON.stringify($scope.formData),  // pass in data as strings
        headers : {'Access-Control-Allow-Origin':'*'}
        })
        .success(function(data) {
            console.log(data);
            if (!data.success) {
            	// if not successful, bind errors to error variables
                $scope.errorName = data.errors.name;
                $scope.errorSuperhero = data.errors.superheroAlias;
            } else {
            	// if successful, bind success message to message
                $scope.message = data.message;
            }
        });
    };

但当我发送我的帖子时,控制台会显示以下错误消息:

-[错误]无法加载资源:Origin htt。。访问控制允许来源不允许。(appForm.php,第0行)

-[错误]XMLHttpRequest无法加载htt。。访问控制允许原点不允许原点http://localhost:8100。(localhost,第0行)

我试着把这个.htaccess放在我的主文件夹中:

页眉添加访问控制允许原点"*"Header add Access Control Allow Headers"origin,x-requested-wwith,content-type"标题添加访问控制允许方法"PUT、GET、POST、DELETE、OPTIONS"

但这增加了另一个错误:

-未能加载资源:服务器的响应状态为500(内部服务器错误)。

我快疯了!有人知道吗?!非常感谢的关注

您可以将服务代理添加到ionic.project文件中。

{
  "name": "appname",
  "email": "",
  "app_id": "",
  "proxies": [
    {
      "path": "/v1",
      "proxyUrl": "https://api.instagram.com/v1"
    }
  ]
}

检查中的相关部件https://github.com/driftyco/ionic-cli

在我的例子中,打开命令行获取chrome目录:

C: ''Program Files(x86)''Google''Chrome''Application

类型:chrome.exe --disable-web-security

在您的浏览器中,转到http://localhost:8100,您的问题将得到解决

在开发阶段,我们需要在离子框架中明确处理交叉起源问题。

以下是来自离子团队的一个很好的博客页面,其中包含问题的完整细节

高级:

步骤1:将代理详细信息添加到ionic.project

{
 "name": "proxy-example",
  "app_id": "",
  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "http://cors.api.com/api"
    }
  ]
}

步骤2:作为一种良好的做法,添加角度常数来管理外部端点-这不是强制性的

angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])
.constant('ApiEndpoint', {
  url: 'http://localhost:8100/api'
})

第三步:重新启动"离子发球"。如果不重新启动ionic.项目更改将不会生效。