错误讯息
No 'Access-Control-Allow-Origin' header is present on the requested resource.
解决方法 1
在 Laravel
安装 laravel-cors
,即可解决。
composer require barryvdh/laravel-cors
解决方法 2
引用 Laravel 处理 OPTIONS 请求的原理探索及批量处理方案
新增中间件 appHttpMiddlewareCors.php
:
发送非简单请求时,伺服器端会先收到一个 OPTIONS 的预请求,前端只有收到这个预请求的正常回应,才会发送正式的 POST 请求。
<?php
namespace AppHttpMiddleware;
use Closure;
class Cors
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $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;
}
}
开启 appHttpKernel.php,新增:
protected $middleware = [
...
AppHttpMiddlewareCors::class,
];