錯誤訊息php
No 'Access-Control-Allow-Origin' header is present on the requested resource.前端
解決方法 1laravel
在 Laravel 安裝 laravel-cors,便可解決。app
composer require barryvdh/laravel-corscors
解決方法 2composer
引用 Laravel 處理 OPTIONS 請求的原理探索及批量處理方案ui
新增中間件 app\Http\Middleware\Cors.php:spa
發送非簡單請求時,伺服器端會先收到一個 OPTIONS 的預請求,前端只有收到這個預請求的正常回應,纔會發送正式的 POST 請求。.net
<?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, ];