簡體   English   中英

在每個 API 請求 nuxtJS 上接收 CORS 策略錯誤

[英]Receiving CORS policy error on every API request nuxtJS

我正在嘗試運行 Laravel V8.14(后端)和 nuxtJS 2.15(前端)應用程序,但不幸的是每個 API 請求(包括 SSR 請求)都在使用WAMP1244B7602ZBCAL計算機上的 Z5A8FEFF0B4BDE3EEC7 錯誤

運行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 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.ZE1BFD762321E409CEE4AC0B6E84193 文件夾中

已經有 5 天了,我陷入了這個困境,主要是我用代理改變東西,希望它下次能工作。甚至完全全新安裝了 nuxtJS(刪除 node_modules 和 package.json.lock)但沒有運氣。

任何幫助將不勝感激。

檢查后端應用程序上的 Corse 策略設置。 可能 AllowedCorsOriginis 設置在一些不同的不同端口上,然后您沒有 Api 請求的許可。 它發生在我身上好幾次。 如果您也在 localhost 上加載后端應用程序,則它的簡單修復。

嘗試改變這部分:

/* * 您可以為 1 個或多個路徑啟用 CORS。 * 示例:['api/*'] */ 'paths' => ['http://localhost:3000'],

您可以檢查是否有任何異常響應,例如die(...)dd(..)exit 這些方法也可能觸發 cors 錯誤。

我相信您收到此錯誤是因為您的請求來源不同; 您正在嘗試從http://localhost:3000的來源請求http://localhost的文檔。

嘗試將您的nuxt.config.js 文件代理object 參數中的目標屬性從http://api.localhost/http://api.localhost:3000/

包括請求和響應標頭的屏幕截圖也可能會有所幫助; 如錯誤所示:

對預檢請求的響應未通過訪問控制檢查:請求的資源上不存在“Access-Control-Allow-Origin”header

,您可能沒有發送在您的情況下是必需的Access-Control-Allow-Origin HTTP-Header

關於這個問題的一些可能有幫助的文檔可以是:

問題是我的 wamp apache配置,我將解釋我為找出導致 CORS 錯誤的原因以及我如何修復它而采取的步驟。

在新的 windows 上安裝所有內容后,我仍然遇到問題,但不是在實時服務器上,所以我認為它一定是我正在運行的web服務器,這就是問題所在。我的ZB6EFD606D3118D0F6206上的配置錯誤部分是:

  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是 a.env laravel 文件變量,它的值是http://localhost在我的例子中,任何與代理相關的內容都應該注釋掉,因為你不能同時使用代理和 baseURL。

在此處閱讀有關 nuxt axios 模塊的更多信息

請記住,您還必須在 httpd.conf 中取消注釋LoadModule headers_module modules/mod_headers.so稱為headers_module

感謝一路上的幫助

問題可能出在 RouteServiceProvider.php 文件中。 您可以嘗試刪除中間件以訪問 API 路由嗎?

Route::prefix('api')
->middleware('api') // <-- delete this
->namespace($this->namespace)
->group(base_path('routes/api.php'));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM