📜  laravel csrf token ajax post - Javascript (1)

📅  最后修改于: 2023-12-03 15:17:12.386000             🧑  作者: Mango

Laravel CSRF Token and AJAX POST with JavaScript

Laravel is a popular PHP web framework that provides developers with a set of tools for building scalable and robust applications. One of the security features of Laravel is the CSRF (Cross-Site Request Forgery) protection. CSRF attacks are a type of malicious attack where an attacker tries to exploit the trust relationship between a user and a web application by forging requests. Laravel provides a built-in mechanism to prevent these types of attacks by adding a CSRF token to every HTML form submitted in the application.

However, this mechanism does not protect AJAX requests sent from JavaScript. In this article, we will learn how to include the CSRF token in an AJAX POST request using JavaScript.

Include CSRF Token in AJAX POST Request

To include the CSRF token in an AJAX POST request, we need to first create a JavaScript variable named csrfToken that holds the value of the CSRF token. Laravel includes the CSRF token in the meta tag of the web page. We can access this value using JavaScript as follows:

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

This code selects the meta tag with the name attribute set to "csrf-token", gets its value using the getAttribute method, and assigns it to the csrfToken variable.

Next, we need to include this value in the AJAX request headers as follows:

let xhr = new XMLHttpRequest();
xhr.open('POST', '/endpoint', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('X-CSRF-TOKEN', csrfToken);
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        // handle response
    }
}
xhr.send(JSON.stringify({data}));

In this code snippet, we create a new XMLHttpRequest object, set its method to POST and its URL to /endpoint. We also set the Content-Type header to application/json to indicate that we are sending data in JSON format. Finally, we set the X-CSRF-TOKEN header to the value of the csrfToken variable that we obtained earlier.

We also set an event listener for the onreadystatechange event, which is fired every time the state of the request changes. Inside the event listener, we check if the readyState is equal to 4 and the status is equal to 200, which indicates that the request was successful. At this point, we can handle the response using JavaScript.

Conclusion

In this article, we learned how to include the CSRF token in an AJAX POST request using JavaScript in a Laravel application. By doing so, we can protect our application from CSRF attacks even when sending requests from JavaScript.