1

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

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

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内核.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 天了,我陷入了这个困境,主要是我用代理改变了东西,希望它下次能工作。甚至完全全新安装了 nuxtJS(删除了 node_modules 和 package.json.lock),但没有运气。

任何帮助将不胜感激。

4

2 回答 2

0

您可以检查是否有任何异常响应,例如die(...)dd(..)exit。这些方法也可能触发 cors 错误。

于 2022-01-05T14:19:03.677 回答
-1

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

在新窗口上安装所有内容后,我仍然面临问题,但不是在实时服务器上,所以我认为它一定是我正在运行的 Web 服务器,这就是问题。我在WAMP上的apache配置的错误部分是:

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

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

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

在我发布的问题中,一切都开始使用相同的配置,并且 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 模块的更多信息

请记住,您也必须在 httpd.conf中LoadModule headers_module modules/mod_headers.so知道未注释headers_module

感谢一路上的帮助

于 2022-01-12T11:37:08.987 回答