It looks like you're trying to set the CSRF token in your Axios interceptor, but you're not actually retrieving the token from anywhere. In a typical Laravel application, the CSRF token is stored in a meta tag within your HTML's head section. You need to retrieve this token and then set it in your Axios requests.
Here's how you can modify your code to include the CSRF token:
First, ensure that your Laravel layout includes the CSRF token meta tag. In your main blade layout file (usually resources/views/layouts/app.blade.php), add the following line inside the <head> section:
<meta name="csrf-token" content="{{ csrf_token() }}">
Next, in your axios.js file, you can retrieve the CSRF token from the meta tag and set it in the Axios interceptor:
import axios from "axios"
export default defineNuxtPlugin((NuxtApp) => {
axios.defaults.baseURL = 'http://localhost:8000'
axios.defaults.withCredentials = true;
axios.interceptors.request.use((config) => {
// Retrieve the CSRF token from the meta tag
const csrfToken = document.head.querySelector('meta[name="csrf-token"]');
if (csrfToken) {
config.headers.common["X-CSRF-TOKEN"] = csrfToken.content;
} else {
console.error('CSRF token not found');
}
return config;
});
return {
provide: {
axios: axios
},
}
})
This code snippet retrieves the CSRF token from the meta tag and sets it in the Axios request headers. If the token is not found, it logs an error to the console.
Make sure that your Nuxt.js application is correctly injecting the CSRF token from your backend into the page where your Nuxt.js app is mounted. If you're using SSR (Server-Side Rendering) with Nuxt.js, you might need to pass the CSRF token from your Laravel backend to your Nuxt.js frontend through props or some other mechanism.
If you're using Laravel as an API backend and Nuxt.js for the frontend, and they are on different domains, you might need to configure CORS and CSRF settings appropriately on the Laravel side to ensure that the CSRF token is accepted from the Nuxt.js domain.