1

我试过以下事情。但是当从反应到 laravel 发送帖子请求时仍然存在 csrf 问题

我已经使用 barryvh 中间件 cors 来修复 cors 问题

在 cors.php 中

'supportsCredentials' => false,
   'allowedOrigins' => ['*'],
   'allowedHeaders' => ['Content-Type', 'X-Requested-With','token','user_token','_token','X-CSRF-TOKEN'],
   'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT',  'DELETE']
   'exposedHeaders' => [],
   'maxAge' => 0,
  1. 页面中的元标记

       return (
          <div className="Login" style={{fontFamily: 'Montserrat, sans-serif',height:'36em'}}>
            <input type="hidden" name="_token" value="{{ csrf_token() }}"></input>
            <meta name="csrf-token" content="{{ csrf_token() }}"/>
            {/* { csrf_token() } */}
            {/* { @csrf } */}
            {/* { csrf_field() }*/}
    
  2. 根中的元标记 (index.html)

  3. 尝试在帖子中遵循注释代码

      return fetch("www.campaignserver.com:3001/test", 
            {
                method: 'post',
                credentials: "same-origin",
                headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json',
                        //"_token": "{{ csrf_token() }}",
                        "X-Requested-With": "XMLHttpRequest",
                        'X-CSRF-TOKEN': document.querySelector("[name~=csrf-token] 
               [content]").content
                    },
    
  4. laravel 端——route.api.php

       // Route::middleware('auth:api')->post('/test', function (Request $request) {
       //     return response()->json(['message' =>'corstest'], 200);
       // });
       // Route::post('test', 'HomeController@test');
      // Route::get('test', 'HomeController@test');
    

我怎样才能确定根本原因。?请建议

4

1 回答 1

4

由于您使用 laravel 作为 api,因此使用 CSRF 令牌没有意义。

默认情况下,当您使用路由文件routes/api.php时,没有 CSRF 令牌验证。您可以验证app/Http/Kernel.php

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class, //<-- HERE IS THE CSRF VERIFICATION
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [ //<--- AS you can see there is no VerifyCsrfToken middleware in API
        \Barryvdh\Cors\HandleCors::class,
        'throttle:300,1', 
        'bindings',
    ],
];

对于您正在调用的路由routes/api.php,默认情况下声明的路由具有前缀,您可以在app\Providers\RouteServiceProvider.php@中检查mapApiRoutes

/**
 * Define the "api" routes for the application.
 *
 * These routes are typically stateless.
 *
 * @return void
 */
protected function mapApiRoutes()
{
    Route::prefix('api') //<-- here is the prefix
         ->middleware('api') //<-- this is the kernel middleware used for this route group
         ->namespace($this->namespace)
         ->group(base_path('routes/api.php')); //<-- and here is the related file
}
于 2019-11-18T08:08:44.433 回答