Ahmed_Ait_Lahcen

Untitled

Nov 3rd, 2023
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. console.log('Pre-request Script from Request start');
  2.  
  3. // We don't need to do anything if it's GET or x-csrf-token header is explicitly presented
  4. if (pm.request.method !== 'GET' && !(pm.request.headers.has('x-csrf-token'))) {
  5.  
  6.   var csrfRequest = pm.request.clone();
  7.   csrfRequest.method = 'GET';
  8.   if (pm.request.method === 'POST') {
  9.     // for POST method usually it is ....<something>Collection in the URL
  10.     // so we add $top=1 just to quickly get csrf token;
  11.     // for PUT, PATCH or DELETE the same URL would be enough,
  12.     // because it points to the actual entity
  13.     csrfRequest.url = pm.request.url + '?$top=1';
  14.   }
  15.  
  16.   csrfRequest.upsertHeader({
  17.     key: 'x-csrf-token',
  18.     value: 'fetch'
  19.   });
  20.  
  21.   pm.sendRequest(csrfRequest, function(err, res) {
  22.     console.log('pm.sendRequest start');
  23.     if (err) {
  24.       console.log(err);
  25.     } else {
  26.       var csrfToken = res.headers.get('x-csrf-token');
  27.       if (csrfToken) {
  28.         console.log('csrfToken fetched:' + csrfToken);
  29.         pm.request.headers.upsert({
  30.           key: 'x-csrf-token',
  31.           value: csrfToken
  32.         });
  33.       } else {
  34.         console.log('No csrf token fetched');
  35.       }
  36.     }
  37.     console.log('pm.sendRequest end');
  38.   });
  39. }
  40.  
  41. console.log('Pre-request Script from Request end');
Add Comment
Please, Sign In to add comment