Laravel 5 + AngularJS跨域CORS

用户名

我到处都在寻找答案,但到目前为止没有任何结果。事实证明,所有列出的堆栈解决方案都不足够。

我以错误的形式在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控制器:

<?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',
]);

of肿的种类不整齐:

//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软件包通过过滤器和控制器中的_construct进行实现的所有方法。我还走了服务器配置路线,尝试将标头添加到.htaccess和virtualhost配置。

拉斐尔·F。

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

我的情况是创建一个设置头文件的中间件是完美的解决方案。

创建一个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,
];

在Routes中,您可以将中间件与group一起使用或直接定向到特定的路由,例如:

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!")
            },
        });

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

在Laravel 5中跨子域的持久会话

来自分类Dev

Laravel-跨域请求-Barryvdh Laravel-Cors

来自分类Dev

HTML5 Web Workers可以/应该将CORS用于跨域吗?

来自分类Dev

在ASP.Net 5 / Core中启用跨域资源共享(CORS)

来自分类Dev

使用NPM的Laravel 5的AngularJS

来自分类Dev

跨域请求阻止Laravel

来自分类Dev

多租户子域在Laravel 5中

来自分类Dev

Laravel 5 Dotenv用于特定子域

来自分类Dev

将Laravel 5与AngularJS刀片标签冲突

来自分类Dev

AngularJS + Laravel 5身份验证

来自分类Dev

jQuery:使用laravel跨域Ajax'POST'

来自分类Dev

跨域图片上传Angular + laravel

来自分类Dev

无法在Laravel 5中为特定路线添加CORS

来自分类Dev

无法在Laravel 5中为特定路线添加CORS

来自分类Dev

如何在laravel5中访问域URL

来自分类Dev

子域路由在Laravel 5上不起作用-WAMPServer

来自分类Dev

Laravel 5基于子域的本地化

来自分类Dev

Laravel 5-根据域设置配置变量

来自分类Dev

Laravel 5子域站点是否作为新项目托管?

来自分类Dev

如何在Laravel 5中的类之间共享作用域

来自分类Dev

同一域上的多个Laravel 5项目

来自分类Dev

Laravel 5子域站点是否作为新项目托管?

来自分类Dev

尝试在laravel 5中配置子域时出错

来自分类Dev

laravel 5子域重定向到主页

来自分类Dev

AngularJS和Laravel-CORS

来自分类Dev

AngularJS跨域发布

来自分类Dev

跨域CORS和图像

来自分类Dev

AngularJS控制器中的Laravel 5雄辩模型对象

来自分类Dev

AngularJS控制器中的Laravel 5雄辩模型对象