javascriptasynchronousauth0hoppscotch

Hoppscotch Pre-request Script async request


I'm experiencing an issue with the asynchronous execution order of .then() in a fetch request within my JavaScript script. The script is supposed to fetch an authentication token and then set it in an environment variable. However, it seems like the URL call for my application is happening before the .then() chains execute, leading to the use of an unset token. I need the token to be retrieved and set before making a subsequent request. So it successfully retrieves the token and the script is being executed until the first part of fetch, but before the .then it calls the url and then executes the rest of the script.

const authUrl = "https://auth0.com/oauth/token";
const authBody = JSON.stringify({
  grant_type: "password",
  client_id: "client_id",
  client_secret: "client_secret",
  scope: "openid profile email",
  audience: "https://audience/",
  username: "username",
  password: "password"
});
console.log("nach dem ziehen des token")
// Execute the fetch request to authenticate
fetch(authUrl, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: authBody
})
.then(response => response.json())
.then(data => {
  if (data.access_token) {
    // Set the access token in an environment variable
    pw.env.set("accessToken", data.access_token);
        pw.env.set("accessToken", data.access_token);
    console.log("accessToken set:", data.access_token); // to check the log
  } else {
    console.error('Error retrieving the token:', data);
  }
})
.catch(error => console.error('Error in fetching auth token:', error));

Solution

  • I solved this issue by declaring a function and the calling that function at the end:

    const authUrl = pw.env.get("auth0_url")+"/oauth/token";
    const authBody = JSON.stringify({
      grant_type: "password",
      client_id: pw.env.get("client_id"),
      client_secret: pw.env.get("client_secret"),
      scope: "openid profile email",
      audience: pw.env.get("audience"),
      username: pw.env.get("username_auth0"),
      password: pw.env.get("password_auth0"),
    });
    
    function authenticate() {
      try {
        const request = new XMLHttpRequest();
        request.open("POST", authUrl, false);
        request.setRequestHeader("Content-Type", "application/json");
        request.send(authBody);
    
        if (request.status === 200) {
          const data = JSON.parse(request.responseText);
          if (data.access_token) {
            pw.env.set("accessToken", data.access_token);
            console.log("accessToken set:", data.access_token); 
            // Zusätzlich überprüfen, ob es korrekt gesetzt wurde
            let token = pw.env.get("accessToken");
            console.log("Retrieved accessToken:", token);
          } else {
            console.error('Error retrieving the token:', data);
            pw.env.set("accessToken", "");
          }
        } else {
          console.error('Error in fetching auth token. Status:', request.status);
          pw.env.set("accessToken", "");
        }
      } catch (error) {
        console.error('Error in fetching auth token:', error);
        pw.env.set("accessToken", "");
      }
    }
    
    // Funktion aufrufen, um die Authentifizierung durchzuführen
    authenticate();