gpt4 book ai didi

Nuxt .js and Laravel API - CSRF token mismatch(Nuxt.js和Laravel API-CSRF令牌不匹配)

转载 作者:bug小助手 更新时间:2023-10-25 22:27:46 24 4
gpt4 key购买 nike



I'm trying to make a login page using nuxt.js as Front-end and Laravel for the API.

我正在尝试使用nuxt.js作为前端,使用Laravel作为API的登录页面。


Unfortunately, after I take the csrf token from sanctum-cookie, I can't use it because of "CSRF token mismatch." I don't know what to do from here.

不幸的是,在我从SASTOM-COOKIE中获取CSRF令牌后,我不能使用它,因为“CSRF令牌不匹配”。我不知道从现在起该怎么办。


Laravel info:

Laravel info:


APP_URL=http://localhost:8080
FRONTEND_URL=http://localhost:3000
SANCTUM_STATEFUL_DOMAINS=http://localhost:8000,localhost:3000,localhost:8000,http://localhost:3000

8080 is the port for LAravel and 3000 is nuxt.

8080是LAravel的港口,3000是nuxt。


Those are the calls to the api and the login is returning an error about CSRF and I have no idea why.

这些是对API的调用,登录返回了一个关于CSRF的错误,我不知道为什么。


// calls from nuxt
async function validate() {

await axios.get('http://localhost:8080/sanctum/csrf-cookie', {
withCredentials: true
});

const token = useCookie('XSRF-TOKEN');

await axios.post('http://localhost:8080/login', {
'email': '[email protected]',
'password': '1234567890'
}, {
headers: {
'X-XSRF-TOKEN': token.value as string
}
})
}

cors.php config

Cors.php配置


    'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => [env('FRONTEND_URL', 'http://localhost:3000')],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,

更多回答
优秀答案推荐

After 3 days ... all i need to do was to add withCredentials: true for the login axios...

三天后...我所需要做的就是为登录AXIOS添加WITH Credentials:True...


Awesome! <3

太棒了!<3



set sanctumn.php :

设置staumn.php:


'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8080,::1',
Sanctum::currentApplicationUrlWithPort()
))),

then set env variable in .env file as given below:

然后在.env文件中设置env变量,如下所示:


FRONTEND_URL=http://localhost:3000
ROOT_URL=//127.0.0.1:8080
APP_URL=http://localhost
SESSION_DRIVER=cookie
SESSION_DOMAIN=.localhost

then run these commands in laravel project:

然后在laravel项目中运行以下命令:


php artisan config:clear && php artisan cache:clear && php artisan optimize && php artisan serve

then in your nuxt login.vue:

然后在您的nuxt登录.vue中:


async function validate() {

await useFetch("http://localhost:8080/sanctum/csrf-cookie", {
credentials: "include",
});

const token = useCookie('XSRF-TOKEN');

await useFetch("http://localhost:8080/api/login", {
credentials: "include",
method: "POST",
body: {
'email': 'email',
'password': 'password'
},
headers: {
'X-XSRF-TOKEN': token.value as string,
},
watch: false
})
// remaining codes...
}

更多回答

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