第一个错误:POST http://62.113.97.194:8000/api/v1/users/token net::ERR_FAILED
const loginUser = async (username, password) => {
try {
const response = await fetch(
"backend endpoint",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
username: username,
password: password,
}),
}
);
if (response.ok) {
const data = await response.json();
setAuthTokens(data);
setUser(jwt(data.access));
localStorage.setItem("authTokens", JSON.stringify(data));
navigate("/");
} else {
const errorData = await response.json();
console.error("Login failed:", errorData);
alert(`Login failed: ${errorData.message}`);
}
} catch (error) {
console.error("An unexpected error occurred during login:", error);
alert(`An unexpected error occurred: ${error.message}`);
}
};
const handleTokenRequest = async () => {
try {
if (!otp) {
console.error(
"Verification code is empty. Please provide a valid code."
);
return;
}
const response = await fetch(
"backend endpoint",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
username: 1,
password: 1,
phone: formData.phoneNumber,
verification_code: otp,
}),
}
);
if (response.ok) {
const responseData = await response.json();
const accessToken = responseData.access;
const refreshToken = responseData.refresh;
// Log tokens in the console
console.log("Access Token:", accessToken);
console.log("Refresh Token:", refreshToken);
loginUser(accessToken, refreshToken);
// Additional logic, such as redirecting the user or showing a success message
} else {
console.error("Token request failed. Something went wrong!");
}
} catch (error) {
console.error("Error during token request:", error);
if (error.response && error.response.status === 404) {
console.error("Invalid verification code or user not found");
}
}
};
第二个错误:
登录时发生意外错误:TypeError: 无法获取 在登录用户 (AuthContext.jsx:15:30) 在handleTokenRequest(index.jsx:159:9)
我尝试与不同组的其他开发人员核实,但不幸的是我没有收到我的问题的答案,我也尝试自己解决问题但我不能,我也尝试找出我的问题的答案来自AI,但没有帮助
以下是潜在问题:
throw new Error("Error happened", error);
所以在获取之后你应该添加类似的东西
if (!response.ok) {
throw new Error("Error happened");
}