我评论中间件Cors和VerifyCsrfToken,但是当我尝试从Laravel发送GET请求时(前端:react),仍返回Cors策略错误

vc9ivgsu  于 2023-06-24  发布在  React
关注(0)|答案(1)|浏览(105)

我评论中间件Cors和VerifyCsrfToken,但是当我尝试从Laravel发送GET请求时(前端:react),仍然返回Cors策略错误。
请求:'http://localhost:3000'接收:'http://127.0.0.1:8000/getCSRFToken'
////////////////////////////////////////////
getCSRFToken是一个写在Laravel HomeController.php文件中的函数,当我使用应用程序POSTMAN来获取请求时,该函数返回令牌没有问题。只有当我尝试使用react发送请求时才会发生错误。

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function getCSRFToken(){
        return csrf_token();
    }
}

这是我的Kernel.php文件

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array<int, class-string|string>
     */
    protected $middleware = [
        \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Illuminate\Http\Middleware\HandleCors::class, 
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
       // \App\Http\Middleware\Cors::class,  commented
        \Illuminate\Session\Middleware\StartSession::class,
        // \App\Http\Middleware\VerifyCsrfToken::class,  commented
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
   
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array<string, array<int, class-string|string>>
     */
    protected $middlewareGroups = [
        'web' => [
            \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, 
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    /**
     * The application's middleware aliases.
     *
     * Aliases may be used instead of class names to conveniently assign middleware to routes and groups.
     *
     * @var array<string, class-string|string>
     */
    protected $middlewareAliases = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \App\Http\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    ];
}

这是我的web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StudentController;
use App\Http\Controllers\HomeController;

Route::get('/getCSRFToken',[HomeController::class,'getCSRFToken']);

/////////////////////////////////////////////////////////////////////////////////////////
我用axios

function onSubmit (e){
    e.preventDefault();
    axios.get('http://127.0.0.1:8000/getCSRFToken')
    .then(res=>{
        console.log(res);
    })
    .catch(error=>{
        console.log(error);
    })

浏览器返回
CORS策略已阻止从源“http://localhost:3000”访问位于“http://127.0.0.1:8000/getCSRFToken”的XMLHttpRequest:当请求的凭据模式为“include”时,响应中“Access-Control-Allow-Origin”标头的值不能为通配符“*”。XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制。
我甚至尝试取消注解VerifyCsrfToken.php,并尝试将/getCSRFToken放入受保护的$exceptarray中,浏览器仍然返回相同的错误。请帮帮忙

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array<int, string>
     */
    protected $except = [
     
      
        '/getCSRFToken',
    ];
}
lb3vh1jj

lb3vh1jj1#

由于前端(http://127.0.0.1:8000/)和后端(http://127.0.0.1:3000/)的URL不同,出现CORS问题。因此,如果您想解决CORS问题,请按照以下步骤操作。
1.在api.php中创建路线

Route::get('test-route', [HomeController::class, 'test_method']);

1.使用此API route with the api prefix,如下图所示。

http://127.0.0.1:8000/api/test-route

1.现在创建自定义中间件来解决CORS问题。

php artisan make:middleware CustomCors

1.将下面的代码放入位于App\Http\Middleware的自定义中间件中。

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;

class CustomCors
{
    public function handle(Request $request, Closure $next)
    {
        return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', '*')
        ->header('Access-Control-Allow-Credentials', true)
        ->header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,X-Token-Auth,Authorization')
        ->header('Accept', 'application/json');
    }
}
?>

1.最后,在kernel.php中为所有路由注册您的自定义中间件,其位置为App\Http\Kernel.php

<?php 
protected $middleware = [
    \App\Http\Middleware\CustomCors::class,
    // Others middlewares
];
?>

相关问题