我在 JavaScript 脚本中的提取请求中遇到了 .then() 异步执行顺序的问题。该脚本应该获取身份验证令牌,然后将其设置在环境变量中。但是,我的应用程序的 URL 调用似乎发生在 .then() 链执行之前,导致使用未设置的令牌。我需要在发出后续请求之前检索并设置令牌。因此,它成功检索了令牌,并且脚本正在执行,直到 fetch 的第一部分,但在 .then 之前,它调用 url,然后执行脚本的其余部分。
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));
我通过声明一个函数并在最后调用该函数解决了这个问题:
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();