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



我正在应用cors中间件从其他域访问json。

这个代码工作得很好:-

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

但当我将其应用于:-

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

它在控制台中给我错误

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

我有一个已经添加的Cors中间件,Cors.php:-

class Cors
{
/**
 * Handle an incoming request.
 *
 * @param  IlluminateHttpRequest  $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');
}
}

请帮忙。谢谢

在将JWT发送到标头时,我也试图为自己的问题找到解决方案。这就是解决我的问题的原因:

1) 在路由中间件中添加cors

protected $routeMiddleware = [
    ...
    'cors' => AppHttpMiddlewareCors::class,
];

2) 在全球middlewre 中添加cors

protected $middleware = [
    ...
    AppHttpMiddlewareCors::class,
];

3) 在Cors中间件应用程序/Http/middleware/Cors.php 中添加自定义访问控制允许标头

<?php namespace AppHttpMiddleware;
use Closure;
use IlluminateHttpRequest;
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
    }
}

相关内容

  • 没有找到相关文章

最新更新