英文:
Failed to load resource: the server responded with a status of 400 (BAD REQUEST)-React
问题
以下是您要翻译的代码部分:
import { createContext, useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import jwtDecode from "jwt-decode";
export const AuthContext = createContext();
function setUserObject(user) {
if (!user) {
return null;
}
return {
username: user.username,
id: user.id,
first_name: user.first_name,
};
}
export const AuthProvider = ({ children }) => {
const BASE_URL = "http://127.0.0.1:5000/api/auth";
const navigate = useNavigate();
const [token, setToken] = useState(localStorage.getItem("token"));
const [user, setUser] = useState(null);
const [isServerError, setIsServerError] = useState(false);
const registerUser = async (registerData) => {
try {
const finalData = {
username: registerData.username,
password: registerData.password,
email: registerData.email,
first_name: registerData.firstName,
last_name: registerData.lastName,
address: registerData.address,
phone: registerData.phone,
};
const response = await axios.post(`${BASE_URL}/register`, finalData);
if (response.status === 201) {
console.log("Successful registration! Log in to access token");
setIsServerError(false);
navigate("/login");
} else {
setIsServerError(true);
console.log("Registration failed.");
}
} catch (error) {
setIsServerError(true);
console.error("An error occurred during registration:", error.response.data);
}
};
const loginUser = async (loginData) => {
try {
const response = await axios.post(`${BASE_URL}/login`, loginData);
if (response && response.status === 200 && response.data && response.data.access) {
const accessToken = response.data.access;
localStorage.setItem("token", accessToken);
setToken(accessToken);
const loggedInUser = jwtDecode(accessToken);
setUser(setUserObject(loggedInUser));
setIsServerError(false);
navigate("/");
} else {
navigate("/register");
}
} catch (error) {
console.log("Error logging in:", error);
setIsServerError(true);
navigate("/register");
}
};
const logoutUser = () => {
localStorage.removeItem("token");
setUser(null);
setToken(null);
navigate("/");
};
const contextData = {
user,
token,
loginUser,
logoutUser,
registerUser,
isServerError,
};
return (
<AuthContext.Provider value={contextData}>{children}</AuthContext.Provider>
);
};
希望这可以帮助您更好地理解代码。如果您需要进一步的翻译或有其他问题,请随时提出。
英文:
I am Useding Axios to for to make a request, the code work so well when testing it with postman, but when I try runing the code on the client side it will fail with the 127.0.0.1:5000/api/auth/register:1 Failed to load resource: the server responded with a status of 400 (BAD REQUEST)
import { createContext, useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import jwtDecode from "jwt-decode";
export const AuthContext = createContext();
function setUserObject(user) {
if (!user) {
return null;
}
return {
username: user.username,
id: user.id,
first_name: user.first_name,
};
}
export const AuthProvider = ({ children }) => {
const BASE_URL = "http://127.0.0.1:5000/api/auth";
const navigate = useNavigate();
const [token, setToken] = useState(localStorage.getItem("token"));
const [user, setUser] = useState(null);
const [isServerError, setIsServerError] = useState(false);
const registerUser = async (registerData) => {
try {
const finalData = {
username: registerData.username,
password: registerData.password,
email: registerData.email,
first_name: registerData.firstName,
last_name: registerData.lastName,
address: registerData.address,
phone: registerData.phone,
};
const response = await axios.post(`${BASE_URL}/register`, finalData);
if (response.status === 201) {
console.log("Successful registration! Log in to access token");
setIsServerError(false);
navigate("/login");
} else {
setIsServerError(true);
console.log("Registration failed.");
}
} catch (error) {
setIsServerError(true);
console.error("An error occurred during registration:", error.response.data);
}
};
const loginUser = async (loginData) => {
try {
const response = await axios.post(`${BASE_URL}/login`, loginData);
if (response && response.status === 200 && response.data && response.data.access) {
const accessToken = response.data.access;
localStorage.setItem("token", accessToken);
setToken(accessToken);
const loggedInUser = jwtDecode(accessToken);
setUser(setUserObject(loggedInUser));
setIsServerError(false);
navigate("/");
} else {
navigate("/register");
}
} catch (error) {
console.log("Error logging in:", error);
setIsServerError(true);
navigate("/register");
}
};
const logoutUser = () => {
localStorage.removeItem("token");
setUser(null);
setToken(null);
navigate("/");
};
const contextData = {
user,
token,
loginUser,
logoutUser,
registerUser,
isServerError,
};
return (
<AuthContext.Provider value={contextData}>{children}</AuthContext.Provider>
);
};
export default AuthContext`
import React, { useContext, useEffect} from "react";
import { Link } from "react-router-dom";
import AuthContext from "../../context/AuthContext";
import useCustomForm from "../../hooks/useCustomForm";
const RegisterPage = () => {
const { registerUser, isServerError } = useContext(AuthContext);
const [formData, handleInputChange, handleSubmit, reset] = useCustomForm(
{
firstName: "",
lastName: "",
username: "",
email: "",
address: "",
phone_number: ""
},
registerUser
);
useEffect(() => {
if (isServerError) {
reset();
}
}, [isServerError, reset]);
return (
<div className="lo-container">
<div className="logbanner"></div>
<div className="login-form">
<form className="form" onSubmit={handleSubmit}>
<h1>New member setup an account</h1>
<div className="form-row"></div>
<label className="form-label">
<input
type="text"
name="firstName"
value={formData.firstName || ""}
onChange={handleInputChange}
placeholder="First Name"
required
/>
</label>
<label className="form-label">
<input
type="text"
name="lastName"
value={formData.lastName || ""}
onChange={handleInputChange}
placeholder="Last Name"
required
/>
</label>
<label className="form-label">
<input
type="text"
name="username"
value={formData.username || ""}
onChange={handleInputChange}
placeholder="Username"
required
/>
</label>
<label className="form-label">
<input
type="password"
name="password"
value={formData.password || ""}
onChange={handleInputChange}
placeholder="Password"
required
/>
</label>
<label className="form-label">
<input
type="email"
name="email"
value={formData.email || ""}
onChange={handleInputChange}
placeholder="Email"
required
/>
</label>
<label className="form-label">
<input
type="text"
name="address"
value={formData.address || ""}
onChange={handleInputChange}
placeholder="Address"
required
/>
</label>
<label className="form-label">
<input
type="tel"
name="phone_number"
value={formData.phone_number || ""}
onChange={handleInputChange}
maxLength="200"
placeholder="Phone Number"
required
/>
</label>
{isServerError ? (
<p className="error">Registration failed, please try again.</p>
) : null}
<button className="login-btn">Register!</button>
<div className="divider">
<span className="divider-text">or</span>
</div>
<p>Already have an account?</p>
<Link to="/login" className="sign-up-btn">
Login
</Link>
</form>
</div>
</div>
);
};
export default RegisterPage;
import React, { useContext, useEffect} from "react";
import { Link } from "react-router-dom";
import AuthContext from "../../context/AuthContext";
import useCustomForm from "../../hooks/useCustomForm";
const RegisterPage = () => {
const { registerUser, isServerError } = useContext(AuthContext);
const [formData, handleInputChange, handleSubmit, reset] = useCustomForm(
{
firstName: "",
lastName: "",
username: "",
email: "",
address: "",
phone_number: ""
},
registerUser
);
useEffect(() => {
if (isServerError) {
reset();
}
}, [isServerError, reset]);
return (
<div className="lo-container">
<div className="logbanner"></div>
<div className="login-form">
<form className="form" onSubmit={handleSubmit}>
<h1>New member setup an account</h1>
<div className="form-row"></div>
<label className="form-label">
<input
type="text"
name="firstName"
value={formData.firstName || ""}
onChange={handleInputChange}
placeholder="First Name"
required
/>
</label>
<label className="form-label">
<input
type="text"
name="lastName"
value={formData.lastName || ""}
onChange={handleInputChange}
placeholder="Last Name"
required
/>
</label>
<label className="form-label">
<input
type="text"
name="username"
value={formData.username || ""}
onChange={handleInputChange}
placeholder="Username"
required
/>
</label>
<label className="form-label">
<input
type="password"
name="password"
value={formData.password || ""}
onChange={handleInputChange}
placeholder="Password"
required
/>
</label>
<label className="form-label">
<input
type="email"
name="email"
value={formData.email || ""}
onChange={handleInputChange}
placeholder="Email"
required
/>
</label>
<label className="form-label">
<input
type="text"
name="address"
value={formData.address || ""}
onChange={handleInputChange}
placeholder="Address"
required
/>
</label>
<label className="form-label">
<input
type="tel"
name="phone_number"
value={formData.phone_number || ""}
onChange={handleInputChange}
maxLength="200"
placeholder="Phone Number"
required
/>
</label>
{isServerError ? (
<p className="error">Registration failed, please try again.</p>
) : null}
<button className="login-btn">Register!</button>
<div className="divider">
<span className="divider-text">or</span>
</div>
<p>Already have an account?</p>
<Link to="/login" className="sign-up-btn">
Login
</Link>
</form>
</div>
</div>
);
};
export default RegisterPage;
I want to be able to register and login a user, Using the postman API to the test the request it work so well
答案1
得分: 0
你应该在服务器端调试以准确了解哪个字段发送了意外数据。
话虽如此,我看到可能有两个问题可能导致 400 错误:
- 在
formData
中,你有一个名为phone_number
的字段,但在发送到服务器之前,你从phone
中读取它,如果phone
未定义并且服务器需要它,这可能导致错误的数据错误。 - 你的 formData 中没有声明名为
password
的字段,所以如果密码没有发送到服务器,这可能会导致问题。
英文:
You should debug this on server side to understand exactly which field is sending unexpected data.
That being said, I see potential 2 problems which might cause 400 error here
- In
formData
you have a field namedphone_number
but before sending it to server, you are reading it fromphone
which might cause bad data error ifphone
is undefined and is required by server. - You do not have a field called
password
declared in your formData so that might cause an issue if password is not sent to the server.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论