我正在使用Angular Js和Laravel。在角度js中,我使用路由提供程序将请求从角度js发送到laravel。
在角度js中,我创建了路径js,其中我使用 $ routeProvider 包含html模板。在这里,下面是 route.js
var app = angular.module("supportApp",['ngRoute']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: '../views/home.html',
controller: 'AdminController'
}).
when('/masters/countries', {
templateUrl: '../views/masters/countries.html'
});
}
]);
现在,我创建了masters.js,其中存储了所有主控制器。在这里你可以看到 masters.js
app.controller('CountriesController',function($scope,$http){
var countries = this;
$http.get("http://api.local.support.com/masters/countries")
.then(function mySuccess(responce) {
countries.countrydata = responce["data"]["data"];
});
this.saveAdd = function() {
console.log(countries.countries);
$http.post("http://api.local.support.com/masters/countries/store",countries.countries)
.then(function mySuccess(response) {
console.log(response);
});
}
});
在这里,我在laravel中创建了中间件来接受来自另一个域的请求。的 Cors.php
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', $_SERVER['HTTP_ORIGIN'])
->header('Access-Control-Allow-Methods', 'POST, OPTIONS')
->header('Access-Control-Allow-Credentials', 'true')
->header('Access-Control-Max-Age', '10000')
->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
}
}
我的countries.html页面如下所示:
<div ng-controller="CountriesController as country">
<div class="modal fade" id="addNew" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header bg-primary">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="icons-office-52"></i></button>
<h4 class="modal-title"><strong>Add New Country</strong> </h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="field-1" class="control-label">Country</label>
<input type="text" class="form-control" name="name" ng-model="country.countries.name">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="field-1" class="control-label">Sortname</label>
<input type="text" class="form-control" name="alias" ng-model="country.countries.sortname">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default btn-embossed" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary btn-embossed" data-dismiss="modal" ng-click="country.saveAdd()">Save</button>
</div>
</div>
</div>
</div>
</div>
这里,角度js中的get方法正在运行。但它在post方法中给出了错误。
错误: XMLHttpRequest无法加载http://api.local.support.com/masters/countries/store。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原点“http://local.support.com”访问。
注意:在这里,我为laravel创建了两个顶点主机http://api.local.support.com
,为角度js和视图文件创建了http://local.support.com
。
那么,我该如何解决这个错误?