带有分组前缀的nuxt的Laravel 7 Cors问题

问题描述

nuxt和laravel 7 Route :: group的新手

更新在这里打开了一个问题:

https://github.com/fruitcake/laravel-cors/issues/487

我的laravel和cors软件包版本:

- "fruitcake/laravel-cors": "^2.0",- "laravel/framework": "^7.24",

我的Api路线

Route::group(['prefix' => 'auth','namespace' => 'Auth'],function () {
    Route::post('signin','SignInController');
    Route::get('me','MeController');
    Route::post('signout','SignOutController');
});

Route::group(['prefix' => 'snippets','namespace' => 'Snippets'],function () {
    Route::post('','SnippetController@store');
    Route::get('{snippet:uuid}','SnippetController@show');
});

身份验证路由有效,但摘要路由无效。

我的心是这样的:

<?PHP

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['api/*','api/snippets','*'],'allowed_methods' => ['*'],'allowed_origins' => ['http://localhost:3000'],'allowed_origins_patterns' => ['*'],'allowed_headers' => ['*'],'exposed_headers' => [],'max_age' => 0,'supports_credentials' => false,];

我也尝试过

<?PHP

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['api/*'],'allowed_origins' => ['*'],];

在每次重试之前,我都使用了PHP artisan config:cache命令。

Cors错误

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/snippets. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

此请求http://localhost:8000/api/snippets/在邮递员中工作正常,但在nuxt中不起作用,我收到了cors错误

有人可以告诉我这里发生了什么吗?

谢谢

解决方法

在laravel中使用dd或任何log函数都会影响cors。

这里是官方网站https://github.com/fruitcake/laravel-cors#echodie

的引文

回声/死 如果在代码中回显(),dd(),die(),exit(),dump()等,则会中断中间件流程。当在标题之前发送输出时,无法添加CORS。当脚本在CORS中间件完成之前退出时,将不会添加CORS标头。始终返回正确的响应或引发异常。

此代码将使其起作用:

public function store(Request $request)
    {
        $snippet = $request->user()->snippets()->create();

        return fractal()
            ->item($snippet)
            ->transformWith(new SnippetTransformer)
            ->toArray();
    }