简体   繁体   English

Laravel 5 CORS中间件不适用于一组路由

[英]Laravel 5 CORS middleware not working for group of routes

I am appling cors middleware to access json from some other domain. 我正在使用cors中间件从其他域访问json。

This code works just fine :- 这段代码很好用: -

Route::get('api/authenticate', ['middleware' => 'cors', function() {
    return Response::json(array('name' => 'Steve Jobs', 'state' => 'California'));
}]);

But when I apply it to :- 但当我申请时: -

Route::group(['prefix' => 'api', 'middleware' => 'cors'], function()
{
    Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
    Route::post('authenticate', 'AuthenticateController@authenticate');
});

it gives me error in console, 它在控制台中给我错误,

No 'Access-Control-Allow-Origin' header is present on the requested resource

I have a have added Cors middleware, cors.php :- 我有一个添加了Cors中间件,cors.php: -

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', '*')->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}

Please help. 请帮忙。 Thanks. 谢谢。

I tried to find solution for mine as well when sending JWT into header. 在将JWT发送到标题时,我也试图找到我的解决方案。 This is what resolved my case: 这就解决了我的情况:

1) Add the cors in route middleware 1)在路由中间件中添加cors

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

2) Add the cors in global middlewre 2)在全球中间添加角色

protected $middleware = [
    ...
    \App\Http\Middleware\Cors::class,
];

3) Add custom Access-Control-Allow-Headers in Cors middleware app/Http/Middleware/Cors.php 3)在Cors中间件app / Http / Middleware / Cors.php中添加自定义Access-Control-Allow-Headers

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Log;

class Cors {
    public function handle($request, Closure $next) {
        Log::info("Using cors for " . $request->url());
        return $next($request)
                ->header('Access-Control-Allow-Origin', '*')
                ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
                ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Request-With');// <-- Adding this
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM