【问题标题】:CORS policy: Request header field x-requested-with is not allowed by Access-Control-Allow-Headers in preflight responseCORS 策略:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 x-requested-with
【发布时间】:2020-03-02 06:16:03
【问题描述】:

完整的错误信息:

从源“http://localhost:3000”访问“https://api_url”处的 XMLHttpRequest 已被 CORS 策略阻止:在预检响应中 Access-Control-Allow-Headers 不允许请求标头字段 x-requested-with。

我无法解决这个 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');
    }
}

【问题讨论】:

    标签: laravel cors axios laravel-vue


    【解决方案1】:

    使用这个包,它会解决你的问题 https://github.com/barryvdh/laravel-cors

    【讨论】:

    • 我看不到它的实现
    • 我用过,但没用。我从 Kernel.php 中的受保护数组 $middleware 中删除它
    • 你能告诉我你是如何使用它的吗?如果您使用的是 api,您只需将其应用到 api 中间件
    • 是的,我添加了这些行。 'api' =&gt; [ \Barryvdh\Cors\HandlePreflight::class, 'throttle:60,1', 'bindings', ],
    • 请更正为\Barryvdh\Cors\HandleCors::class,放在api数组中间件的最后
    【解决方案2】:

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

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

    '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"
    

    【讨论】:

      猜你喜欢
      • 2017-03-03
      • 2020-02-27
      • 2020-10-31
      • 2016-05-15
      • 2019-11-06
      • 2021-12-16
      • 1970-01-01
      • 2016-04-24
      • 2019-02-21
      相关资源
      最近更新 更多