T
T
tol642020-06-22 21:01:43
Laravel
tol64, 2020-06-22 21:01:43

Laravel + Nuxt: How to overcome error 419 - CSRF token mismatch?

Test on localhost

  • Server side of the Laravel application for API requests: localhost:8080
  • Client side on Nuxt : localhost:3000


I will list the main parts for maximum brevity.

Each time (Nuxt), loading any page ( localhost:3000 ), before rendering in the nuxtServerInit () method, a post request is made to get the data:

export const actions = {
    async nuxtServerInit({ state }) {
        await this.$axios.post('/init')
        .then((result) => {
            state.data = result.data;
        });
    }
}


In the controller (Laravel), we send the token in the response:

public function index(Request $request)
    {
        $state = array(
            'token' => csrf_token()
        );
    
        return json_encode($state);
    }


In app\Http\Kernel.php file :

protected $middlewareGroups = [
        ...
        'api' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,

            \App\Http\Middleware\VerifyCsrfToken::class,

            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];


To prevent this request from being rejected, you need to specify a main route exception in app\Http\Middleware\VerifyCsrfToken.php :

class VerifyCsrfToken extends Middleware
{
    protected $except = [
        'api/init'
    ];
}


Now, for the test, we will create a vue page with a form (below is a shortened version) and we will send it using a custom method:

<form @submit.prevent="submit">
  ...
</form>


Below is the script part on the same page. Here we get the token from the storage, which was previously received in the request before rendering the page in the nuxtServerInit () method.

<script>
export default {
    components: {
    },
    data() {
        return {
            form: {
                _token: this.$store.getters.params.token,
                name: '',
                email: '',
                message: ''
            }
        }
    },
    methods: {
        async submit() {
            await this.$axios.post('contacts', this.form)
            .then((result) => {
                console.log('post >', result.data);
            });
        }
    }
}
</script>


We try to send data from the form and get an error:

419: CSRF token mismatch.

What is wrong in this scheme? How to get a token that can then be used in post requests with such a simple example?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin B., 2020-06-22
@Kostik_1993

CSRF is not needed with Nuxt and Laravel. You are doing everything wrong. I advise you to first learn the basics of the tools used

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question