我正在使用以下代碼獲取用戶 idtoken,并且可以使用 console.log 成功地將其記錄到控制臺:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
user.getIdToken().then(function(idToken) {
console.log("IDTOKEN:",idToken);
});
}
});
我現在正在嘗試使用 axios 在請求中將令牌作為標頭發送,如下所示:
async updatebalance() {
let id = this.props.id;
if (id === null || id === undefined) {
id = "test";
}
var res = await axios.post(backUrl "account/user_load_balance", {
uid: localStorage.getItem("account-info"),
id: id,
idToken
});
if (res.data !== null && res.data.status && res.data.balance !== null && res.data.balance !== []) {
this.props.dispatch(etherBalanceLoaded(res.data.balance[0]));
this.props.dispatch(tokenBalanceLoaded(res.data.balance[1]));
}
this.setState({
showbuttonFlag: true
});
this.reset_values();
}
但是我收到以下錯誤:
'idToken' 未定義
我想我可能需要將其設定為全域變數,以便它可以用于不同的功能,但我不知道如何。我怎樣才能做到這一點?
解決方案1:
async updatebalance() {
let id = this.props.id;
if (id === null || id === undefined) {
id = "test";
}
const user = firebase.auth().currentUser
if (user) {
const idToken = await user.getIdToken();
var res = await axios.post(backUrl "account/user_load_balance", {
uid: localStorage.getItem("account-info"),
id: id,
idToken
});
} else {
console.log("User not logged in")
}
if (res.data !== null && res.data.status && res.data.balance !== null && res.data.balance !== []) {
this.props.dispatch(etherBalanceLoaded(res.data.balance[0]));
this.props.dispatch(tokenBalanceLoaded(res.data.balance[1]));
}
this.setState({ showbuttonFlag: true });
this.reset_values();
}
reset_values() {
this.setState({ ethAmount: "" });
this.setState({ sellethAmount: "" });
this.setState({ ethPrice: "" });
this.setState({ sellethPrice: "" });
this.setState({ methAmount: "" });
this.setState({ methPrice: "" });
this.setState({ msellethAmount: "" });
this.setState({ msellethPrice: "" });
}
uj5u.com熱心網友回復:
您可以getIdToken()在 Axios 請求之前使用并傳遞它,如下所示:
const user = firebase.auth().currentUser
if (user) {
// user logged in
const idToken = await user.getIdToken()
var res = await axios.post(backUrl "account/user_load_balance", {
uid: localStorage.getItem("account-info"),
id: id,
idToken
});
if (res.data !== null && res.data.status && res.data.balance !== null && res.data.balance !== []) {
this.props.dispatch(etherBalanceLoaded(res.data.balance[0]));
this.props.dispatch(tokenBalanceLoaded(res.data.balance[1]));
}
this.setState({
showbuttonFlag: true
});
this.reset_values();
} else {
console.log("User not logged in")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/503880.html
標籤:Google Cloud Collective javascript 反应 火力基地 axios firebase 身份验
上一篇:我想讓導航欄變粘
下一篇:SVG沒有完全影片
