錯誤訊息
No 'Access-Control-Allow-Origin' header is present on the requested resource.
解決方法 1
在 Laravel 安裝 laravel-cors,即可解決。
composer require barryvdh/laravel-cors
解決方法 2
新增中介軟體 app\Http\Middleware\Cors.php
:
傳送非簡單請求時,伺服器端會先收到一個
OPTIONS
的預請求,前端只有收到這個預請求的正常回應,才會傳送正式的POST
請求。
<?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)
{
$response = $next($request);
$response->header('Access-Control-Allow-Origin', '*');
if ($request->getMethod() === 'OPTIONS') {
$response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
$response->header('Access-Control-Allow-Credentials', 'true');
$response->header('Access-Control-Allow-Headers', 'Authorization, Content-Type, X-PINGOTHER');
}
return $response;
}
}
開啟 app\Http\Kernel.php
,新增:
protected $middleware = [
...
\App\Http\Middleware\PrecheckCors::class,
];
本作品採用《CC 協議》,轉載必須註明作者和本文連結