我一直在試圖解決這個問題一段時間,但無法破解它。Laravel CORS中間件無法發佈帖子和資源請求
我有一個Laravel後端和角前端。由於前端需要成爲網絡和移動科爾多瓦應用程序,因此它們位於不同的域中。
即使加入CORS中間件,郵政和資源請求後會加載失敗,我在控制檯中看到一個
No 'Access-Control-Allow-Origin' header is present on the requested resource
錯誤。
下面的GET請求沒有很好地工作: -
Route::get('example', ['middleware' => 'cors', function(){
return Response::json(array('name' => 'Steve Jobs 1', 'company' => 'Apple'));
}]);
但其後的失敗 -
Route::group(['middleware' => 'cors'], function() {
Route::group(['prefix' => 'api'], function()
{
Route::resources('authenticate', 'AuthenticateController', ['only' => ['index']]);
Route::post('authenticate', '[email protected]');
});
});
我下面https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps。
我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);
}
}
kernal.php
class Kernel extends HttpKernel
{
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
/*\App\Http\Middleware\VerifyCsrfToken::class,*/
];
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,
'cors' => 'App\Http\Middleware\CORS',
];
}
你可以發佈你的請求返回的HTTP響應代碼嗎?我最近遇到類似的問題,我的迴應是返回一個500的代碼,一個內部服務器錯誤。原來,這與我的標題無關,但事實是我沒有正確地做CSRF。禁用CSRF使其工作。也許嘗試一下,看看它是否真的是一個CORS問題或其他類似於我的情況? –
好吧,我看到你禁用CSRF的地方,所以不是這樣。但是,瞭解HTTP響應代碼可以提供一些見解。 –