manchenkoff / nuxt-auth-sanctum

Nuxt module for Laravel Sanctum authentication
https://manchenkoff.gitbook.io/nuxt-auth-sanctum/
MIT License
116 stars 16 forks source link

Use $fetch to handle requests to api from inside a function where we should not use useAsyncData #89

Closed andyjamesn closed 1 month ago

andyjamesn commented 1 month ago

I have been unable to get my requests to work when using useFetch I get a CSRF token mismatch error.

Then I found useSanctumClient in your docs. Using this things started to work.

But I am using this with PUT and DELETE methods called by a button within a function

According to Nuxt useFetch and useAsyncData as used on the useSanctumClient code example should not be called outside of setup and the Vue context like a delete function.

https://github.com/nuxt/nuxt/discussions/25602

Also Nuxt adds a warning in the console to use $fetch instead.

CleanShot 2024-05-07 at 02 21 21@2x

manchenkoff commented 1 month ago

Hey @andyjamesn, could you please provide a code example that triggers this error?

Composable useSanctumClient returns an instance of $fetch, so you can use it directly without using useAsyncData like

const sanctumFetch = useSanctumClient()

// keeps auto mapping into ResponseDto
const responseObject = sanctumFetch<ResponseDto>('/api/endpoint', {method: 'PUT'})
// returns raw response, so you can access status code, headers, etc
const responseRaw = sanctumFetch.raw('/api/endpoint', {method: 'DELETE'})
andyjamesn commented 1 month ago

Thanks, I figured this out but I was working on my delete method which was failing with a fetch failed so thought I was still doing something wrong.

As it turns out this was a known DELETE empty body issue in unjs or ofetch based on this thread.

https://github.com/unjs/h3/issues/375

I upgraded to 20.11 and it solved the issue.

Thanks for the help, this can be closed now.