adityar15
1 month ago
418
6
Laravel

419 error for Sanctum API post request.

Posted 1 month ago by adityar15

My cors.php looks like this

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Laravel CORS Options
    |--------------------------------------------------------------------------
    |
    | The allowed_methods and allowed_headers options are case-insensitive.
    |
    | You don't need to provide both allowed_origins and allowed_origins_patterns.
    | If one of the strings passed matches, it is considered a valid origin.
    |
    | If array('*') is provided to allowed_methods, allowed_origins or allowed_headers
    | all methods / origins / headers are allowed.
    |
    */

    /*
     * You can enable CORS for 1 or multiple paths.
     * Example: ['api/*']
     */
    'paths' => ['api/*','sanctum/csrf-cookie'],

    /*
    * Matches the request method. `[*]` allows all methods.
    */
    'allowed_methods' => ['*'],

    /*
     * Matches the request origin. `[*]` allows all origins.
     */
    'allowed_origins' => ['*'],

    /*
     * Matches the request origin with, similar to `Request::is()`
     */
    'allowed_origins_patterns' => [],

    /*
     * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
     */
    'allowed_headers' => ['*'],

    /*
     * Sets the Access-Control-Expose-Headers response header with these headers.
     */
    'exposed_headers' => [],

    /*
     * Sets the Access-Control-Max-Age response header when > 0.
     */
    'max_age' => 0,

    /*
     * Sets the Access-Control-Allow-Credentials header.
     */
    'supports_credentials' => true,
];

My ajax get request works perfectly fine. The problem is with AJAX POST request. I am constantly getting 419 error. I have included X-XSRF-TOKEN header in my ajax headers. On document ready, I am firing a function which looks like this

  fetch('/sanctum/csrf-cookie')
  .then(response => console.log(response))
  .then(data => console.log(data));

This function creates XSRF-TOKEN cookie which I am using in my ajax header as

t = gettoken('XSRF-TOKEN');
$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
    'X-XSRF-TOKEN': t,
    'Authorization': "Bearer {{env('bearer_token')}}"
  },
  async:false
});

The get token function is nothing but cookie retrieving function. Even after all of this, I am getting 419 error. What could be the reason? Any solution? Thanks in advance :)

Please sign in or create an account to participate in this conversation.