Level 2
Create a util in utils/larafetch
import { useAuthStore } from "~/stores/auth";
const CSRF_COOKIE = "XSRF-TOKEN";
const CSRF_TOKEN = "X-Xsrf-Token";
export async function larafetch(path, options = {}) {
const { backendURL, frontendURL } = useRuntimeConfig().public;
//get token
let token = useCookie(CSRF_COOKIE).value;
if (
process.client &&
["post", "delete", "put", "patch"].includes(
options?.method?.toLowerCase() ?? ""
) &&
!token
) {
await initCsrf();
token = getCookie(CSRF_COOKIE);
}
//set headers
let headers = {
...options.headers,
accept: "application/json",
[CSRF_TOKEN]: token,
};
if (process.server) {
headers = {
...headers,
...useRequestHeaders(["cookie"]),
referer: frontendURL,
};
}
//fetch operation
const result = await useFetch(path, {
...options,
baseURL: backendURL,
credentials: "include",
headers,
});
//handle error
const { error, status } = result;
if (status.value === "success") {
return result;
} else {
//handle 401 here
switch (error.value.statusCode) {
case 401:
case 419:
const authStore = useAuthStore();
authStore.user = null;
navigateTo("/login");
break;
case 409:
navigateTo("/verifyemail");
break;
case 500:
console.log("server error");
break;
default:
return result;
}
}
}
async function initCsrf() {
const { backendURL } = useRuntimeConfig().public;
await useFetch("/sanctum/csrf-cookie", {
baseURL: backendURL,
credentials: "include",
server: false,
});
}
function getCookie(name) {
const match = document.cookie.match(
new RegExp("(^|;\s*)(" + name + ")=([^;]*)")
);
return match ? decodeURIComponent(match[3]) : null;
}
use case example
async function login(form) {
conts { error, status } = await larafetch("/login", { method: "post", body: form });
//todo
}
use case example 2
const { data } = await larafetch(`/dashboard/posts`);
Also when using default useFetch include "credentials:include" option, i.e.,
const { data } = await useFetch(`/posts`, {credentials: "include", baseURL: backendURL,});
1 like