[英]Updated object not being returned properly in nextjs
所以基本上我正在开发一个使用身份验证的 nextjs 应用程序。 我有 2 个函数,我在每次页面加载时运行。 第一个检查 jwt cookies 是否存在,如果令牌不存在,则调用另一个 function 来验证令牌。 这个 function 从 wrapper.getServerSideProps 运行,并作为 ctx 在上下文中传递。 此 function 按预期工作。
export const checkServerSideCookie = (ctx) => {
const access = getCookie("access", ctx.req);
const refresh = getCookie("refresh", ctx.req);
if (access && refresh) {
return checkAuthentication(access, refresh);
} else return { isAuthenticated: false, token: null };
};
第二个 function 是令牌验证器,这就是问题出现的地方。 我有一个 object,如果验证成功,我打算更新它,如果不成功,就别管它。 这是 function
export const checkAuthentication = (access, refresh) => {
const obj = {
isAuthenticated: false,
token: null,
};
const body = JSON.stringify({ token: access });
axios
.post("http://localhost:8000/api/jwtoken/verify/", body, {
headers: {
"Content-Type": "application/json",
},
})
.then((res) => {
obj.isAuthenticated = true;
obj.token = access;
})
.catch((err) => {
// call new token function using refresh
console.log("it doesnt work");
});
return obj;
};
问题是.then确实更新了 object,当我在.then中的 console.log(obj) 显示要返回的正确 obj 时,但是当我返回 obj 时,它仍然保留初始值 false 和 null . 我不明白问题是什么。 我尝试在.then 本身中进行返回,但它通过此错误TypeError: Cannot destructure property 'isAuthenticated' of 'Object(...)(...)' as it is undefined
。 这里有什么问题? 一切看起来都很好,但更新后的 obj 没有返回。
axios.post
是异步的,您在它被 api 响应中的数据填充之前返回obj
,您可以使用async/await
来解决这个问题:
export const checkAuthentication = async (access, refresh) => {
const obj = {
isAuthenticated: false,
token: null
};
const body = JSON.stringify({ token: access });
try {
const res = await axios.post("http://localhost:8000/api/jwtoken/verify/", body, {
headers: {
"Content-Type": "application/json"
}
});
obj.isAuthenticated = true;
obj.token = access;
} catch (e) {
// do something with the error
// call new token function using refresh
console.log("it doesnt work");
}
return obj;
};
用法( checkAuthentication
现在返回 promise ):
checkAuthentication(a, b).then((obj) => {
console.log(obj);
});
当您调用checkAuthentication
时,它会立即返回具有默认属性的obj
。 您在 function 中指定了一个异步操作,但是您不要等到它完成。 您必须通过以下方式重建您的 function:
export const checkAuthentication = (access, refresh) => {
const obj = {
isAuthenticated: false,
token: null,
};
const body = JSON.stringify({ token: access });
return new Promise((resolve, reject) => {
axios
.post("http://localhost:8000/api/jwtoken/verify/", body, {
headers: {
"Content-Type": "application/json",
},
})
.then((res) => {
resolve({
isAuthenticated: true,
token: access
})
})
.catch((err) => {
// call new token function using refresh
console.log("it doesnt work");
reject();
});
});
};
然后通过以下方式调用您的 function:
checkAuthentication(access, refresh)
.then(console.log)
.catch(console.log)
当然,您有多种选择可以使您的 function 更清洁,例如使用async
/ await
等,但这应该可以让您快速了解问题所在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.