How can I get data from api when backend is secured by laravel sanctum?
when I use useFetch
I do not get any data.
const {data: cat} = await useFetch('/api/categories')
Laravel docs told to use axios but in nuxt3 axios module not working. Can someone help?
I was try use useFetch
with method get to get csrf cookie but it's doesn't work
const {data} = await useFetch('/sanctum/csrf-cookie', {method: 'get'}).then(Response => {
})
To get data when using sanctum,
You are already getting the csrf token above by going to the route /sanctum/csrf-cookie.
However, that is not enough.
For every request that you want to make which is secured, you need to send a token that is generated using sanctum.
Usually, for an app, you would follow these steps
$user->createToken('TokenName');
"Authorization": "Bearer " + TOKEN_VALUE;
All depends how you are sending the request.
More documentation is available On this link on Laravel Documentation
Also, ensure you have
Accept: Application/json
As part of your headers as well.
If you do not send that token in your headers, your requests will give you an error "Unauthenticated".
Below is an example of what I send to the API
And for Authorization, select the option of Bearer Token
Hope this helps.
The endpoint /sanctum/csrf-cookie
does not return content in the body of the response, that's why you get HTTP 204 No Content
, during this request Laravel Sanctum will set an XSRF-TOKEN
cookie containing the current CSRF token, you have two ways to use the token: it can be passed via X-XSRF-TOKEN
header from your requests, or from the original XSRF-TOKEN
cookie.
https://laravel.com/docs/9.x/sanctum#csrf-protection
Here's an exemple using the XSRF-TOKEN cookie:
// the browser load the XSRF-TOKEN cookie
await fetch("https://myapi.com/sanctum/csrf-cookie", {
"method": "GET",
"mode": "cors",
"credentials": "include"
});
// now the browser can send a POST request
await fetch("https://myapi.com/api/register", {
"method": "POST",
"body": JSON.stringfy({name: 'Joe': email: 'joe@gmail.com'})
"mode": "cors",
"credentials": "include"
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.