angularjs - Laravel 5 + AngularJS 跨域 CORS

标签 angularjs cors laravel-5

我到处寻找答案,但到目前为止没有任何效果。堆栈上列出的所有解决方案尚未被证明是足够的。

我的 laravel 日志中没有任何错误形式的信息,我只得到标准:

XMLHttpRequest cannot load http://api.domain.dev/post/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://domain.dev' is therefore not allowed access.

Laravel Controller :

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Post;
use App\Tag;
use Illuminate\Http\Request;

class PostController extends Controller {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {

        $posts = Post::with('user', 'tags')->get();

        return response()->json($posts);
    }
}

Laravel 路线:

<?php

Route::resource('user', 'UserController');
Route::resource('post', 'PostController');
Route::get('post/tag/{tag}', 'PostController@postsWithTag');
Route::resource('tag', 'TagController');

Route::controllers([
    'auth' => 'Auth\AuthController',
    'password' => 'Auth\PasswordController',
]);

有点臃肿、没有组织的 Angular :

//App
var app = angular.module('app', [
    'ngRoute',
    'ngAnimate'
    ]);

//Config
app.config(['$routeProvider', '$locationProvider', '$animateProvider', function($routeProvider, $locationProvider, $animateProvider) {

    $locationProvider.html5Mode(true).hashPrefix('!');

    $routeProvider.
    when('/', {
        templateUrl: 'partials/home.html',
        controller: 'PageController'
    }).
    when('/about', {
        templateUrl: 'partials/about.html',
        controller: 'AboutController'
    }).
    when('/contact', {
        templateUrl: 'partials/contact.html',
        controller: 'ContactController'
    }).
    when('/blog', {
        templateUrl: 'partials/blog.html',
        controller: 'PostsController'
    }).
    when('/blog/post/:postId', {
        templateUrl: 'partials/post.html',
        controller: 'PostController'
    }).
    otherwise({
        redirectTo: '/'
    });


}]);

//Factory
app.factory('Data', function Data($http) {

    return {
        getPosts: function getPosts() { return $http.get('http://api.domain.dev/post/'); },
        getPost: function getPost(id) { return $http.get('http://api.domain.dev/post/' + id); },
        addPost: function addPost(data) { return $http.post('http://api.domain.dev/post/', data); },
        removePost: function removePost(id) { return $http.delete('http://api.domain.dev/post/'+ id); },

        getTags: function getTags() { return $http.get('http://api.domain.dev/tag/'); },
        getTag: function getTag(id) { return $http.get('http://api.domain.dev/tag/' + id); },
        addTag: function addTag(data) { return $http.post('http://api.domain.dev/tag/', data); },
        removeTag: function removeTag(id) { return $http.delete('http://api.domain.dev/tag/'+ id); },

    } 
}); 

//Posts Controller
app.controller('PostsController', function PostsController($scope, Data) {



    Data.getPosts().success(parsePosts);

    function parsePosts(data) { 
        $scope.posts = data; 
    }

    //AddPost
    $scope.newPost = { title: '', content: '', resume: '' };

    $scope.addPost = function addPost(){Data.addPost({ title: $scope.newPost.title, content: $scope.newPost.content, resume: $scope.newPost.resume, user_id: $scope.newPost.user_id }).success(postAddSuccess).error(postAddError);}

    function postAddSuccess(data) {
        $scope.error = null;
        $scope.posts.push(data);
        $scope.newPost = { title: '', content: '', resume: '' }; 
    }

    function postAddError(data) { 
        $scope.error = data; 
    }

    //RemovePost
    $scope.removePost = function removePost(id) {
        if (confirm('Do you really want to remove this post?')) {
            Data.removePost(id).success(postRemoveSuccess); 
        } 
    }

    function postRemoveSuccess(data) {
        var i = $scope.posts.length;
        while (i--) {
            if ($scope.posts[i].id == data) {
                $scope.post.splice(i, 1);
            }
        }
    }

});

//Post Controller
app.controller('PostController', function PostController($scope, $routeParams, Data) {
    Data.getPost($routeParams.id).success(parsePost);

    function parsePost(data) {
        $scope.post = data;
    }

    Data.getTags($routeParams.id).success(parsePostsTags);

    function parsePostsTags(data) {
        $scope.tags = data;
    }

    $scope.newTag = { tag: '' };

    $scope.addTag = function addTag() {
        $scope.newTag.post_id = $scope.post.id;
        Data.addTag($scope.newTag).success(tagAddSuccess).error(tagAddError);
    }

    function tagAddSuccess(data) {
        $scope.error = null;
        $scope.tags.push(data);

        $scope.newTag = { tag: '' };
    }

    function tagAddError(data) {
        $scope.error = data;
    }

    $scope.removeTag = function removeTag(id) {
        if (confirm('Do you really want to remove this tag?')) {
            Data.removeTag(id).success(tagRemoveSuccess);
        }
    }

    function tagRemoveSuccess(data) {
        var i = $scope.tags.length;
        while (i--) {
            if ($scope.tags[i].id == data) {
                $scope.tags.splice(i, 1);
            }
        }
    }
});

//About Controller
app.controller('AboutController', function AboutController($scope, Data) {



});

//Portfolio Controller
app.controller('PortfolioController', function PortfolioController($scope, Data) {



});

//Contact Controller
app.controller('ContactController', function ContactController($scope, Data) {



});

//Page Controller
app.controller('PageController', function PageController($scope, Data) {



});

我不知道从这里该去哪里。 我已经尝试了从正常的 header() 实现到使用 laravel-cors 包通过过滤器和 Controller 中的 _construct 实现的一切。 我还选择了服务器配置路线,并尝试将 header 添加到 .htaccess 和虚拟主机配置中。

最佳答案

我也遇到了同样的问题,但是使用 jQuery,我花了几周时间才得到一个好的解决方案。

我的案例创建一个中间件来设置 header 是完美的解决方案。

创建Cors中间件:App\Http\Middleware\Cors.php

namespace App\Http\Middleware;

use Closure;

class Cors
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', $_SERVER['HTTP_ORIGIN'])
            // Depending of your application you can't use '*'
            // Some security CORS concerns 
            //->header('Access-Control-Allow-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');
    }
}

记住在 App\Http\Kernel 中设置 Cors 别名

protected $routeMiddleware = [
    ...
    'cors' => \App\Http\Middleware\Cors::class,
];

在路由内部,您可以将中间件与组一起使用或直接指向特定路由,例如:

Route::match(['post', 'options'], 'api/...', 'Api\XController@method')->middleware('cors');

如果有人在使用 jQuery 时遇到这个问题,我建议使用 $.ajax,而不是 $.get、$.post。当您使用此方法时,jQuery 使用 XMLHttpRequest 发送数据并将 content-type 设置为 application/x-www-form-urlencoded,这是不可能更改的,因此,请使用 Ajax。

例如:

        $.ajax({
            type: 'POST',
            url: 'www.foo.bar/api',
            contentType: "application/json",
            xhrFields: {
                // The 'xhrFields' property sets additional fields on the XMLHttpRequest.
                // This can be used to set the 'withCredentials' property.
                // Set the value to 'true' if you'd like to pass cookies to the server.
                // If this is enabled, your server must respond with the header
                // 'Access-Control-Allow-Credentials: true'.
                withCredentials: true

            },

            headers: {
                // Set any custom headers here.
                // If you set any non-simple headers, your server must include these
                // headers in the 'Access-Control-Allow-Headers' response header.
                'Accept': 'application/json'
            },



            data: '{"some":"json data"}',
            success: function (data) {
                console.log('AJAX version');
                console.log("Works!")
            },
        });

记住:如果您在请求 header 上使用 application/json,则必须提供“OPTIONS”方法来进行预检。

有关 CORS 的更多信息:http://www.html5rocks.com/en/tutorials/cors/

关于angularjs - Laravel 5 + AngularJS 跨域 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29045413/

相关文章:

c# - .NET Core 中的 CORS

node.js - 为 PouchDB 启用 CORS 以与 CouchDB 配合使用

使用 AJAX 时未加密 Laravel session cookie

拉拉维尔 5 : How to create a router model binding on multiple parameters

php - 如何回滚php artisan make :auth in laravel 5的效果

javascript - AngularJS 在 Wordpress 插件中工作吗

javascript - 使用在 firefox 中不起作用的 javascript 创建和打开文件

javascript - 如何使用angularjs从数组中删除时间

javascript - 如何从Angularjs中的下拉列表中获取选定的值?

asp.net-web-api - mvc webapi 跨域发布