7

我有一个由Valet提供的Laravel网站和一个Nuxt SPA 。当我尝试使用Nuxt Auth模块对Sanctum进行身份验证时,出现以下 CORS 错误:backend.testnuxt.backend.test:3005

从源“ http://nuxt.backend.test:3005 ”访问“ http://backend.test/login ”处的 XMLHttpRequest已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”标头在请求的资源上。

我该如何解决?

Laravel 配置

config/cors.php

<?php

return [
    'paths' => ['*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
];

routes/api.php

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

app/Http/Kernel.php

    protected $middlewareGroups = [
        ...
        'api' => [
            EnsureFrontendRequestsAreStateful::class,
            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

.env

SANCTUM_STATEFUL_DOMAINS="backend.test"
SESSION_DOMAIN=".backend.test"

Nuxt配置 nuxt.config.js

export default {
  server: {
    port: '3005',
    host: 'nuxt.backend.test'
  },
  ...
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/auth-next'
  ],
  axios: {
    proxy: true
  },
  proxy: {
    '/nuxt': {
      target: 'nuxt.backend.test',
      pathRewrite: { '^/nuxt': '/' }
    }
  },
  auth: {
    redirect: {
      callback: '/auth/callback'
    },
    strategies: {
      laravelSanctum: {
        provider: 'laravel/sanctum',
        url: 'http://backend.test'
      }
    }
  },
  ...
}

pages/index.php

<template>
  <div>
    <div>
      <pre>{{ $auth.user }}</pre>
    </div>
    <button @click="signIn()">Sign in</button>
  </div>
</template>

<script>
export default {
  methods: {
    signIn() {
      this.$auth.loginWith('laravelSanctum', {
        data: {
          email: 'me@home.com',
          password: '1qaz@WSX'
        }
      })
    }
  }
}
</script>
4

1 回答 1

3

Laravel后端和Nuxt前端必须在同一个域下,所以我最终通过 3 个步骤修复了它:

1. 将此添加到/etc/hosts

127.0.0.1   nuxt.backend.test

2. 使用测试版@nuxt/auth

npm remove @nuxtjs/auth
npm install @nuxtjs/auth-next @nuxtjs/axios

nuxt.config.js中,使用:

  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/auth-next'
  ],

3. 使用以下配置:

{
  axios: {
    proxy: true
  },
  proxy: {
    '/laravel': {
      target: 'http://backend.test',
      pathRewrite: { '^/laravel': '/' }
    }
  },
  auth: {
    strategies: {
      laravelSanctum: {
        provider: 'laravel/sanctum',
        url: '/laravel'
      }
    }
  }
}

或者,替换backend.test和删除Nuxt服务器,然后使用Laravel代替Valet可以。nuxt.backend.testlocalhosthostnuxt.config.jsphp artisan serve

于 2020-06-03T06:31:34.220 回答