「PHP」Laravel 接收非简单请求出现的 OPTIONS 请求问题

错误讯息

No 'Access-Control-Allow-Origin' header is present on the requested resource.

解决方法 1

Laravel 安装 laravel-cors,即可解决。

composer require barryvdh/laravel-cors

解决方法 2

引用 Laravel 处理 OPTIONS 请求的原理探索及批量处理方案

新增中间件 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\Cors::class,
];
posted @ 2021-06-04 03:31  ColdJk  阅读(331)  评论(0编辑  收藏  举报