How Does Laravel Add X-XSRF-TOKEN Automatically When Requesting Via Axios?
I have a API that uses the same auth
middleware. So when I am successfully logged in, I am redirected to a page that gets data from my API from the same app. In my app.blade.php
I only have axios added and a simple html and take note, I don't even have a csrf-token
meta in my header except from my login page which has @csrf
in my form.
Here is my app.blade.php
layout
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
@yield('content')
<script src="{{ asset('js/axios.min.js') }}"></script>
<script>
const http = axios.create({
baseURL: '/api'
});
http.interceptors.request.use((request) => {
console.log('Starting Request', request);
return request;
});
</script>
@stack('scripts')
</body>
</html>
and in one of my pages:
@extends('layouts.app')
@section('content')
<div>
<h1>Hello World</h1>
</div>
@endsection
@push('scripts')
<script>
async function test() {
const { data } = await http('/some-page');
// I'm getting a data even without passing a csrf token?
console.log(data);
}
test();
</script>
@endpush
I'm getting the API data even without passing a csrf/xsrf token which is weird.
When I check my console for logs of outgoing request, this is the output
I mean, where did that came form? I don't even have a csrf token in my templates and also nothing or whatsoever passed to my axios config.
Am I missing something here?
Answer
Check the docs on XSRF token:
X-XSRF-TOKEN
Laravel stores the current CSRF token in a
XSRF-TOKEN
cookie that is included with each response generated by the framework. You can use the cookie value to set theX-XSRF-TOKEN
request header.This cookie is primarily sent as a convenience since some JavaScript frameworks and libraries, like Angular and Axios, automatically place its value in the
X-XSRF-TOKEN
header.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM