【发布时间】:2016-02-07 16:03:19
【问题描述】:
我添加了一个 CORS 中间件,它适用于单个路由:-
Route::get('example', ['middleware' => 'cors', function(){
return Response::json(array('name' => 'Steve Jobs', 'company' => 'Apple'));
}]);
但是当我将它应用于路由组时,它会在控制台中出现错误:-
(index):1 XMLHttpRequest cannot load http://jotdot.mysite.com/api/authenticate.
Response to preflight request doesn't pass access control
check: No 'Access-Control-Allow-Origin' header is present on
the requested resource. Origin 'http://jotdotfrontend.mysite.com' is
therefore not allowed access.
我的路线组:-
Route::group(['middleware' => 'cors'], function () {
Route::group(['prefix' => 'api'], function()
{
Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
Route::post('authenticate', 'AuthenticateController@authenticate');
});
});
Cors.php
class CORS
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
header("Access-Control-Allow-Origin: *");
// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
];
if($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
$response->header($key, $value);
return $response;
return $next($request);
}
}
我正在关注https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps 并尝试在不同的域上设置后端和前端。
谢谢
【问题讨论】:
标签: laravel laravel-5 cross-domain cors middleware