程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Laravel 5 + AngularJS跨域CORS大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决Laravel 5 + AngularJS跨域CORS?

开发过程中遇到Laravel 5 + AngularJS跨域CORS的问题如何解决?下面主要结合日常开发的经验,给出你关于Laravel 5 + AngularJS跨域CORS的解决方法建议,希望对你解决Laravel 5 + AngularJS跨域CORS有所启发或帮助;

我遇到了同样的问题,但是使用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/

解决方法

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

我以错误的形式在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/',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: '',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配置。

大佬总结

以上是大佬教程为你收集整理的Laravel 5 + AngularJS跨域CORS全部内容,希望文章能够帮你解决Laravel 5 + AngularJS跨域CORS所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。