在每个 API 请求 nuxtJS 时收到 CORS 策略错误

Receiving CORS policy error on every API request nuxtJS

我正在尝试 运行 Laravel V8.14(后端)和 nuxtJS 2.15(前端)应用程序,但不幸的是每个 API 请求(包括 SSR 请求)都在获取 CORS 策略我的 LOCAL 计算机使用 WAMP

时出错

运行 npm run dev 一切都被编译并开始监听 http://localhost:3000/ 。 当我尝试访问我的 homepage.but 时,控制台或命令提示符上没有错误 api 请求获取 CORS 策略错误。 我已经尝试使用 nuxtJS 进行 baseURL 和代理,但是错误始终保持不变 time.I 我知道你不能同时拥有这两个

Laravel cors.php 配置文件

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Laravel CORS Options
    |--------------------------------------------------------------------------
    |
    | The allowed_methods and allowed_headers options are case-insensitive.
    |
    | You don't need to provide both allowed_origins and allowed_origins_patterns.
    | If one of the strings passed matches, it is considered a valid origin.
    |
    | If array('*') is provided to allowed_methods, allowed_origins or allowed_headers
    | all methods / origins / headers are allowed.
    |
    */

    /*
     * You can enable CORS for 1 or multiple paths.
     * Example: ['api/*']
     */
   'paths' => ['api/*'],

    /*
    * Matches the request method. `[*]` allows all methods.
    */
    'allowed_methods' => ['*'],

    /*
     * Matches the request origin. `[*]` allows all origins. Wildcards can be used, eg `*.mydomain.com`
     */
    'allowed_origins' => ['*'],

    /*
     * Patterns that can be used with `preg_match` to match the origin.
     */
    'allowed_origins_patterns' => [],

    /*
     * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
     */
    'allowed_headers' => ['*'],

    /*
     * Sets the Access-Control-Expose-Headers response header with these headers.
     */
    'exposed_headers' => [],

    /*
     * Sets the Access-Control-Max-Age response header when > 0.
     */
    'max_age' => 0,

    /*
     * Sets the Access-Control-Allow-Credentials header.
     */
    'supports_credentials' => false,
];

nuxt.config.js 文件

     axios:{
     //baseURL : process.env.CLIENT_URL, //Cant be used with proxy
     proxy:true,
        browserBaseURL: process.env.CLIENT_URL + '/api', // client url
      prefix: '/api/',
            common: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': 'application/json, text/plain, */*',
            }
            },
            proxy: {
              '/api/': { target: 'http://api.localhost/', pathRewrite: {'^/api/': ''}, changeOrigin: true }
            },

Laravel 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
     */
    protected $middleware = [
     \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\SetLocale::class,
       ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    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,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
'minify' =>[
     \RenatoMarinho\LaravelPageSpeed\Middleware\InlineCss::class,
    \RenatoMarinho\LaravelPageSpeed\Middleware\ElideAttributes::class,
    \RenatoMarinho\LaravelPageSpeed\Middleware\InsertDNSPrefetch::class,
    \RenatoMarinho\LaravelPageSpeed\Middleware\RemoveComments::class,
    \RenatoMarinho\LaravelPageSpeed\Middleware\TrimUrls::class,
    \RenatoMarinho\LaravelPageSpeed\Middleware\RemoveQuotes::class,
    \RenatoMarinho\LaravelPageSpeed\Middleware\CollapseWhitespace::class,
        ],
        'api' => [
            //'throttle:60,1',
            'bindings',
            
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
          'admin' => \App\Http\Middleware\Adminmiddleware::class,
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    ];

    /**
     * The priority-sorted list of middleware.
     *
     * This forces non-global middleware to always be in the given order.
     *
     * @var array
     */
    protected $middlewarePriority = [
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\Authenticate::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Illuminate\Auth\Middleware\Authorize::class,
    ];
}

确切错误

Access to XMLHttpRequest at 'http://localhost/api/dashboard/getusercompanyfresh'
 from origin 'http://localhost:3000' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check:
 No 'Access-Control-Allow-Origin' header is present on the requested resource.

所有 API 请求都在路由文件夹 laravel api.php 中

我已经坚持了 5 天,主要是我用代理更改了一些东西,希望它接下来能正常工作 time.even 完全全新安装了 nuxtJS(删除了 node_modules 和 package.json.lock)但运气不好。

如有任何帮助,我们将不胜感激。

您可以查看是否有die(...)dd(..)exit等异常响应。 这些方法也可能触发 cors 错误。

问题出在我的 wamp apache 配置上,我将解释我为找出导致 CORS 错误的原因以及我如何修复它而采取的步骤。

在全新的 windows 上安装所有内容后,我仍然面临这个问题,但 不是 在实时服务器上,所以我认为它一定是我的网络服务器'm 运行 那是我在 WAMPapache 配置的 issue.The 错误部分是:

  DocumentRoot "${INSTALL_DIR}/www/laravel/"
  <Directory "${INSTALL_DIR}/www/laravel/">

我在 httpd.confhttpd-vhosts.conf 中都有。将上面的内容更改为 (添加 laravel 的 public 文件夹) :

  DocumentRoot "${INSTALL_DIR}/www/laravel/public"
  <Directory "${INSTALL_DIR}/www/laravel/public">

在我发布的问题中,一切都开始使用 SAME 配置,并且 CORS 策略错误消失了。

我还测试了另一种方法,您可以删除代理,nuxt.config.js 文件中的 axios 设置如下:

  axios:{
    baseURL : process.env.CLIENT_URL, //Cant be used with proxy
      browserBaseURL: process.env.CLIENT_URL + '/api', // client url
            common: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': 'application/json, text/plain, */*',
            }
            },

其中 CLIENT_URL 是一个 .env laravel 文件变量,在我的例子中它的值为 http://localhost 任何与代理相关的东西都应该是评论是因为您不能同时使用代理和 baseURL。

详细了解 nuxt axios 模块 here

请记住,您也必须在 httpd.conf 中取消对 LoadModule headers_module modules/mod_headers.so 称为 headers_module 的注释

感谢一路上的帮助