Search code examples
laravellaravel-5swaggerswagger-ui

Swagger UI requestInterceptor throws the "Cannot set property 'X-CSRF-TOKEN' of undefined" error


I'm using Laravel 5.7 and Swagger to create API documentation.

composer require:

"require": {
    "php": ">=5.6.4",
    "darkaonline/l5-swagger": "^5.7.3",
    "filp/whoops": "~2.0",
    "laravel/framework": "5.7.*",
    "laravel/passport": "~4.0",
    "laravel/tinker": "~1.0",
    "mll-lab/laravel-graphql-playground": "^2.1",
    "nuwave/lighthouse": "^4.15",
    "paragonie/random_compat": "~2.0",
    "zircote/swagger-php": "3.*"
},

Everything is working OK, but when I try to execute a request in Swagger UI, I get an error:

actions.js:453
TypeError: Cannot set property 'X-CSRF-TOKEN' of undefined

This is the code that throws the error:

 requestInterceptor: function() {
      this.headers['X-CSRF-TOKEN'] = 'hM4lUy0ednXXWEFwYc1iRprnSuBuPwQH6Z4pi6v8';
      return this;
    },

Why does the error occur?


Solution

  • Your requestInterceptor function is missing an argument.

    The requestInterceptor function must have one argument, say, req. This argument provides access to the request data. The function must return the modified request.

    requestInterceptor: function(req) {
      req.headers['X-CSRF-TOKEN'] = 'hM4lUy0ednXXWEFwYc1iRprnSuBuPwQH6Z4pi6v8';
      return req;
    },