Laravel API CORS 模式不工作

Laravel API CORS mode not working

我做了很多研究,并实现了以下中间件来解决我不断遇到的 CORS 错误...

Middleware/Cors.php

<?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)
{
    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS')
        ->header('Access-Control-Allow-Headers', 'content-type');
    }
}

?>

Kernel.php

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'cors' => App\Http\Middleware\Cors,
];

Routes.php

Route::post('/content', array('middleware' => 'cors', 'uses' => 'Test@save'));

这似乎配置正确。但是当我使用 fetch API...

发出请求时
fetch('http://laravel.dev/content', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin':'*'
        },
        body: JSON.stringify({

        })
    })
    //.then((response) => response.json())
    .then((response) => response.text()) 
    .then((text) => {
        console.log(text);
    });

我仍然收到此错误...

Fetch API cannot load http://laravel.dev/content. 
Response to preflight request doesn't pass access 
control check: No 'Access-Control-Allow-Origin' header 
is present on the requested resource.

我尝试将 no-cors 模式添加到我的获取响应中,它成功了,我得到了一个不透明的响应,但我需要 cors 模式才能获得正确的请求。

可能值得注意的是,我的 App 和 Laravel restAPI 位于 XAMPP 上的同一个 htdocs 文件夹中。我不确定这是否是个问题。

我也尝试在 Routers.php 文件的顶部添加 headers,但我仍然遇到同样的错误。我什至可以使用 laravel 配置 restAPI 吗?

尝试移除

->header('Access-Control-Allow-Headers', 'content-type');

class Cors 像这样

<?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)
       {
          return $next($request)
           ->header('Access-Control-Allow-Origin', '*')
           ->header('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');

       }
  }

 ?>

对me.I有效希望对你有帮助