CORS策略:飞行前响应中Access-Control-Allow-Headers不允许使用请求标头字段x-requested-with

完整的错误消息:

  

从原点“ https://api_url”到“ http://localhost:3000”的XMLHttpRequest的访问已被CORS策略阻止:请求标头字段x-requested-with不允许access-Control-Allow-Headers中的飞行前反应。

我无法解决这个cors问题。

我的vue组件代码:

test(){
  axios.get("https://api_url")
  .then(response => {
        this.data = response.data.data;
  });
}

我还创建了一个中间件并将其添加到$middleware中受保护的数组Kernel.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-Credentials','true')
            ->header('access-Control-Allow-Methods','GET,HEAD,OPTIONS,POST,PUT')
            ->header('access-Control-Max-Age','3600')
            ->header('access-Control-Allow-Headers','Origin,accept,Content-Type,X-Requested-With');
    }
}
bendan0663 回答:CORS策略:飞行前响应中Access-Control-Allow-Headers不允许使用请求标头字段x-requested-with

使用此软件包,它将解决您的问题 https://github.com/barryvdh/laravel-cors

,

像@Mohammed Aktaa建议的那样使用此软件包:https://github.com/barryvdh/laravel-cors

HandleCors中间件添加到api中的$middlewareGroup app/Http/Kernel.php数组中:

'api' => [
    // ...
    \Barryvdh\Cors\HandleCors::class,],

发布程序包的配置:

$ php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

编辑配置以对允许的来源使用CORS_ORIGIN环境变量:

'allowedOrigins' => [env('CORS_ORIGIN','')],

在您的.env文件中,为您的本地来源添加一个条目:

CORS_ORIGIN="http://localhost:3000"
本文链接:https://www.f2er.com/3156710.html

大家都在问