Browse Source

Clean up CSRF token fetch

shalvah 3 years ago
parent
commit
a56eafe1c2
2 changed files with 13 additions and 14 deletions
  1. 4 6
      config/scribe.php
  2. 9 8
      resources/js/tryitout.js

+ 4 - 6
config/scribe.php

@@ -187,21 +187,19 @@ return [
         'base_url' => null,
 
         /**
-         * Fetch the CSRF token before each request. This is required if you are using Laravel Sanctum
+         * Fetch a CSRF token before each request. Needed if you're using Laravel Sanctum.
          */
         'use_csrf' => false,
 
         /**
-         * The URL to set the sessions CSRF token for the application
-         * Only used when 'use_csrf' is not set to false
+         * The URL to fetch the CSRF token from (if `use_csrf` is true).
          */
         'csrf_url' => '/sanctum/csrf-token',
 
         /**
-         * The name of the cookie to set when making requests
-         * Only used when 'use_csrf' is not set to false
+         * The name of the cookie to fetch the CSRF token from after hitting the `csrf_url`.
          */
-        'csrf_cookie_name' => 'X-XSRF-TOKEN',
+        'csrf_cookie_name' => 'XSRF-TOKEN',
     ],
 
     /*

+ 9 - 8
resources/js/tryitout.js

@@ -5,15 +5,15 @@ function getCookie(name) {
         return null;
     }
 
-    const xsrfCookies = document.cookie.split(';')
+    const cookies = document.cookie.split(';')
         .map(c => c.trim())
         .filter(c => c.startsWith(name + '='));
 
-    if (xsrfCookies.length === 0) {
+    if (cookies.length === 0) {
         return null;
     }
 
-    return decodeURIComponent(xsrfCookies[0].split('=')[1]);
+    return decodeURIComponent(cookies[0].split('=')[1]);
 }
 
 function tryItOut(endpointId) {
@@ -224,13 +224,14 @@ async function executeTryOut(endpointId, form) {
         }
     }
 
-    const preflightPromise = window.useCsrf && window.csrfUrl ? makeAPICall('GET', window.csrfUrl, {}, {}, {}, null).then(() => {
+    let preflightPromise = Promise.resolve();
+    if (window.useCsrf && window.csrfUrl) {
+        preflightPromise = makeAPICall('GET', window.csrfUrl, {}, {}, {}, null).then(() => {
             headers['X-XSRF-TOKEN'] = getCookie(window.csrfCookieName);
+        });
+    }
 
-            return makeAPICall(method, path, body, query, headers, endpointId);
-        }) : makeAPICall(method, path, body, query, headers, endpointId);
-
-    preflightPromise
+    return preflightPromise.then(() => makeAPICall(method, path, body, query, headers, endpointId))
         .then(([responseStatus, responseContent, responseHeaders]) => {
             handleResponse(endpointId, responseContent, responseStatus, responseHeaders)
         })