Laravel and Vue: Dealing with a Common CSRF Error in Two Similar Projects

I am currently working on two projects that have the same Laravel base code, but one project has a more advanced Vue.js part. Recently, I encountered a strange error message in the JavaScript console.

CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token

In an attempt to troubleshoot, I copied the older version of the functional Vue code from the advanced project, only to face the same error. Interestingly, the copied code worked perfectly in the other project.

Both projects share the same bootstrap code which is as follows:

window._ = require('lodash');

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

try {
    window.$ = window.jQuery = require('jquery');

    require('bootstrap-sass');
} catch (e) {}

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Next we will register the CSRF Token as a common header with Axios so that
 * all outgoing HTTP requests automatically have it attached. This is just
 * a simple convenience so we don't have to attach every token manually.
 */

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

To further investigate, I added a test in the bootstrap.js code like this:

console.log(token);

However, the result came out empty.

At this point, I am at a loss on what steps to take next. Any suggestions?

Answer №1

The initial step is to establish it within the meta tag located in the html header :

<meta name="csrf-token" content="{{ csrf_token() }}" />

Answer №2

consider utilizing window.token in place of token

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Images in the public/image folder cannot be loaded due to a 403 Forbidden error in Laravel, Vue.js,

Although the image in my profile is displayed perfectly, I have encountered an error in the console. When trying to access the image from the public folder, no error occurs. However, if I attempt to access it from the image folder, which is a subfolder, th ...

What is the process for generating a variable script within an HTML tag using document.write?

Here is the code snippet: <script>var posterimage=/images/videos/intro/iamge01.png;</script> <script>document.write('<video controls="controls" height="300" id="video-playlist" poster="VARIABLE" preload="none" src="video.mp4" wid ...

What is the best way to assign a class to a read-only field in HTML and CSS?

My situation is as follows: I have jQuery code that uses an if-statement to add a specific class to an element based on the selected value on a form page. I also created another form where users can view the details of a previously filled out form. However ...

Ensuring Laravel REST API protects specific methods and allows access based on role restrictions

In my project built with Laravel, I have implemented a REST API to provide public data and allow logged-in users to manage membership-related information. Within the dashboard, there are various React components - some that fetch asynchronous data and othe ...

Different Categories of Array Deconstruction

While iterating through an array, I am utilizing destructuring. const newArr = arr.map(({name, age}) => `${name} ${age}`) An error occurs in the above code stating: Binding element 'name' implicitly has an 'any' type To resolve th ...

Instead of using <div>, try substituting it with a different HTML page

Seeking assistance on an HTML page project that involves jQuery, CSS, and HTML without server-side integration. Encountering an issue when attempting to replace a <div> with content from another HTML file saved on my computer. The main page code sni ...

Using a JavaScript "for each" loop instead of having several "if

Could you please provide guidance on where to proceed? There are multiple input rows, with each row containing a field with the class row_changed If the value in the field is greater than 0, ajax will send the entire row to PHP. Each row is wrapped in a ...

Modify follow status once axios request is completed in Vue

I have a requirement to update the follow and unfollow button following an axios request. <template> <div v-if="isnot"> <a href="#" @click.prevent="unfellow" v-if="isfollowing" >unFellow</a> <a href="#" @cli ...

Guide on converting a GraphQL request string into an object

Seeking assistance with intercepting and parsing GraphQL queries/mutations from a POST request body in an Apollo lambda server environment running on Node.js. The requests do not come in JSON format, but as GraphQL query language. I have been unable to fi ...

Steps for running a function upon activation of a React Router:

I'm currently using Reacter Router to manage the routes of my application. For authentication, I am utilizing an OAuth system that provides my application with the following URL: http://localhost/login-meli?code=1234567890 Every time this particular ...

Symfony2: Using Ajax to send data to a controller

I have implemented a search input on my website that allows users to search for content within my database. I want this search input to function similarly to the search bar on Facebook, using Ajax for instant searching. Despite trying various code snippets ...

Provide the 'URL' of an image in JavaScript

Is it possible to retrieve the image address of an img tag using JavaScript without accessing the src attribute directly? Interestingly, Google Chrome provides a way to copy the image address by right-clicking on an img tag and selecting 'Copy image ...

Retrieve a specific quantity of items from an array

I recently started using Postman to develop some test cases. Many of the responses I receive with the get method contain large arrays with numerous objects (I have simplified them here for readability, but each object actually has over 20 properties). Cu ...

Displaying a custom error page in Next.js with the appropriate status code

I recently implemented a custom error page following the instructions provided in the documentation. My goal was to use this error page for specific errors that may occur during the getStaticProps function. Here's how I structured it: const Page: Next ...

Is the jqm flipswitch with the label on the left and the switch on the right?

My goal is to display multiple flipswitches on a mobile app page. This is the code I am using: <div class="ui-content"> <form> <fieldset> <div data-role="fieldcontain"> <label for="checkbox-based-flipswitch" ...

How can I arrange a specific array position in Vuejs according to the Id value?

<div v-for="(item, index) in gr" :key="space.id" class="val-name"> </div> After making a few modifications to the API call logic, I was able to achieve my desired outcome. However, the issue lies in the fact that ...

The AngularJs Wizard Validation Inputfield is unable to locate the scope

Hello all, I am new to AngularJs and encountering an issue with my code. Currently, my HTML structure looks like this: <div class="wizardContainer"> <wizard on-finish="finishedWizard()"> <wz-step title="1"> <h1>Questio ...

Version 5 of Material UI has a bug where the Grid component does not properly stretch

How can I make the Grid component stretch when one of the Card components contains extra text? You can view the sample code here. Changing the alignItems property to "flex-end" or "center" works, but when using alignItems: "stretch" it does not work. I ...

visit a new page with each reload

Can I navigate to a new page without refreshing the current window.location.href? I attempted to achieve this using a jQuery event handler on the window object, however, it doesn't seem to be functioning properly. $(window).on('reload', fu ...

Encountering a series of frustrating 404 errors when attempting to submit a React form multiple times

I've been working on developing a new forum using Express and React, but I'm facing challenges with saving form data to the database. Currently, my goal is to store topic titles in a MongoDB collection, with plans to expand to include message con ...