gpt4 book ai didi

cors - Laravel Sanctuary : blocked by CORS policy with Nuxt Auth module

转载 作者:行者123 更新时间:2023-12-03 14:42:27 25 4
gpt4 key购买 nike

我有一个 Laravel 网站由 Valet 提供服务在 backend.test努克特 SPA 上 nuxt.backend.test:3005 .当我尝试向 Sanctum 进行身份验证时与 Nuxt Auth模块,我得到下面的CORS错误:

Access to XMLHttpRequest at 'http://backend.test/login' from origin 'http://nuxt.backend.test:3005' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.



我该如何解决?

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>

最佳答案

Laravel 后端和 努克特 前端必须在同一个域下,所以我最终通过 3 个步骤修复了它:
1. 将此添加到/etc/hosts :

127.0.0.1   nuxt.backend.test
2. 使用 @nuxt/auth的beta版本:
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.testnuxt.backend.test通过 localhost并删除 努克特 服务器 host来自 nuxt.config.js然后使用 php artisan serve而不是 代客对于 Laravel 也很好。

关于cors - Laravel Sanctuary : blocked by CORS policy with Nuxt Auth module,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62115781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com