Laravel 5 + AngularJS Cross Domain CORS

后端 未结 7 1523
暖寄归人
暖寄归人 2020-12-31 23:28

I have searched everywhere for an answer but nothing have worked so far. All the listed solutions on stack have not proven to be sufficient.

I get nothing in my lar

相关标签:
7条回答
  • 2020-12-31 23:34

    Add these lines in your public/index.php:

    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token'); // allow certain headers 
    

    See, if that works.

    0 讨论(0)
  • 2020-12-31 23:35

    I had the same problem, but with jQuery and took me weeks to get a good solution.

    I my case create an middleware to set headers was the perfect solution.

    Create a Cors middleware: 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');
        }
    }
    

    Remember to set Cors alias inside App\Http\Kernel

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

    Inside Routes you can use middleware with group or direct to an specific route, in e.g.:

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

    If someone have this problem with jQuery, I recommend to use $.ajax, instead of $.get, $.post. When you use this methods, jQuery send data using XMLHttpRequest and set content-type to application/x-www-form-urlencoded, it's impossible to change that, so, use Ajax.

    e.g.:

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

    Remember: If you are using application/json on request header you must provide "OPTIONS" method, to do a preflight.

    More info about CORS: http://www.html5rocks.com/en/tutorials/cors/

    0 讨论(0)
  • 2020-12-31 23:40

    add

    <?php header("Access-Control-Allow-Origin: *"); ?>
    

    to public/index.php if it doesn't work in the function like blue bells suggested

    0 讨论(0)
  • 2020-12-31 23:41

    what i have done but not sure if that is the best solution but there are no cors with that one

    1.build the angular normally using ng build --prod

    2.move the content of angular/dist to laravel/public

    3.then use this simple code in laravel/routes/web.php

    Route::prefix('api')->group(function () {
        Route::get('/', function () {
        return view('welcome');
        });
    });
    Route::get('/{params?}', function () {
    //    return view('welcome');
        include_once '../public/index.html';
    })->where('params', '(.*)');
    

    now all requests comes to Laravel and if it can catch the request with a route this route will work otherwise it will pass it to angular

    0 讨论(0)
  • 2020-12-31 23:52

    I don't have good knowledge in laravel.but My suggestion is to the request headers to access REST Methods(GET,POST,PUT,DELTE) and origin to specific domain from which domain your making request in the following way or else set to '*'(it allows any domain)

    header('Access-Control-Allow-Origin', 'some url');
    header('Allow', 'GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Request-With');
    header('Access-Control-Allow-Credentials', 'true');
    

    At angular js.If you use <1.2 you can set CORS in controller file like following way.In latest version not required it will set default.you need to set what content type your expecting from server default is json.If your expecting other type of content you can set manually in the request.

    myApp.config(['$httpProvider', function($httpProvider) {
                $httpProvider.defaults.useXDomain = true;
                delete $httpProvider.defaults.headers.common['X-Requested-With'];
            }
        ]);
    
    0 讨论(0)
  • 2020-12-31 23:52

    When you invoke a cross origin XHR request, javascript first fires an OPTIONS request to the given URL. If this method hasnt added in your routes, then it pops a 404 page which is served without the ACAO header so the concrete POST request wont be sent, as javascript see it not allowed to.

    0 讨论(0)
提交回复
热议问题