Failed to load resource: the server responded with a status of 400 (BAD REQUEST)-React

huangapple go评论63阅读模式
英文:

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 &quot;react&quot;;
import { useNavigate } from &quot;react-router-dom&quot;;
import axios from &quot;axios&quot;;
import jwtDecode from &quot;jwt-decode&quot;;
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 }) =&gt; {
const BASE_URL = &quot;http://127.0.0.1:5000/api/auth&quot;;
const navigate = useNavigate();
const [token, setToken] = useState(localStorage.getItem(&quot;token&quot;));
const [user, setUser] = useState(null);
const [isServerError, setIsServerError] = useState(false);
const registerUser = async (registerData) =&gt; {
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(&quot;Successful registration! Log in to access token&quot;);
setIsServerError(false);
navigate(&quot;/login&quot;);
} else {
setIsServerError(true);
console.log(&quot;Registration failed.&quot;);
}
} catch (error) {
setIsServerError(true);
console.error(&quot;An error occurred during registration:&quot;, error.response.data);
}
};
const loginUser = async (loginData) =&gt; {
try {
const response = await axios.post(`${BASE_URL}/login`, loginData);
if (response &amp;&amp; response.status === 200 &amp;&amp; response.data &amp;&amp; response.data.access) {
const accessToken = response.data.access;
localStorage.setItem(&quot;token&quot;, accessToken);
setToken(accessToken);
const loggedInUser = jwtDecode(accessToken);
setUser(setUserObject(loggedInUser));
setIsServerError(false);
navigate(&quot;/&quot;);
} else {
navigate(&quot;/register&quot;);
}
} catch (error) {
console.log(&quot;Error logging in:&quot;, error);
setIsServerError(true);
navigate(&quot;/register&quot;);
}
};
const logoutUser = () =&gt; {
localStorage.removeItem(&quot;token&quot;);
setUser(null);
setToken(null);
navigate(&quot;/&quot;);
};
const contextData = {
user,
token,
loginUser,
logoutUser,
registerUser,
isServerError,
};
return (
&lt;AuthContext.Provider value={contextData}&gt;{children}&lt;/AuthContext.Provider&gt;
);
};
export default AuthContext`
import React, { useContext, useEffect} from &quot;react&quot;;
import { Link } from &quot;react-router-dom&quot;;
import AuthContext from &quot;../../context/AuthContext&quot;;
import useCustomForm from &quot;../../hooks/useCustomForm&quot;;
const RegisterPage = () =&gt; {
const { registerUser, isServerError } = useContext(AuthContext);
const [formData, handleInputChange, handleSubmit, reset] = useCustomForm(
{
firstName: &quot;&quot;,
lastName: &quot;&quot;,
username: &quot;&quot;,
email: &quot;&quot;,
address: &quot;&quot;,
phone_number: &quot;&quot;
},
registerUser
);
useEffect(() =&gt; {
if (isServerError) {
reset();
}
}, [isServerError, reset]);
return (
&lt;div className=&quot;lo-container&quot;&gt;
&lt;div className=&quot;logbanner&quot;&gt;&lt;/div&gt;
&lt;div className=&quot;login-form&quot;&gt;
&lt;form className=&quot;form&quot; onSubmit={handleSubmit}&gt;
&lt;h1&gt;New member setup an account&lt;/h1&gt;
&lt;div className=&quot;form-row&quot;&gt;&lt;/div&gt;
&lt;label className=&quot;form-label&quot;&gt;
&lt;input
type=&quot;text&quot;
name=&quot;firstName&quot;
value={formData.firstName || &quot;&quot;}
onChange={handleInputChange}
placeholder=&quot;First Name&quot;
required
/&gt;
&lt;/label&gt;
&lt;label className=&quot;form-label&quot;&gt;
&lt;input
type=&quot;text&quot;
name=&quot;lastName&quot;
value={formData.lastName || &quot;&quot;}
onChange={handleInputChange}
placeholder=&quot;Last Name&quot;
required
/&gt;
&lt;/label&gt;
&lt;label className=&quot;form-label&quot;&gt;
&lt;input
type=&quot;text&quot;
name=&quot;username&quot;
value={formData.username || &quot;&quot;}
onChange={handleInputChange}
placeholder=&quot;Username&quot;
required
/&gt;
&lt;/label&gt;
&lt;label className=&quot;form-label&quot;&gt;
&lt;input
type=&quot;password&quot;
name=&quot;password&quot;
value={formData.password || &quot;&quot;}
onChange={handleInputChange}
placeholder=&quot;Password&quot;
required
/&gt;
&lt;/label&gt;
&lt;label className=&quot;form-label&quot;&gt;
&lt;input
type=&quot;email&quot;
name=&quot;email&quot;
value={formData.email || &quot;&quot;}
onChange={handleInputChange}
placeholder=&quot;Email&quot;
required
/&gt;
&lt;/label&gt;
&lt;label className=&quot;form-label&quot;&gt;
&lt;input
type=&quot;text&quot;
name=&quot;address&quot;
value={formData.address || &quot;&quot;}
onChange={handleInputChange}
placeholder=&quot;Address&quot;
required
/&gt;
&lt;/label&gt;
&lt;label className=&quot;form-label&quot;&gt;
&lt;input
type=&quot;tel&quot;
name=&quot;phone_number&quot;
value={formData.phone_number || &quot;&quot;}
onChange={handleInputChange}
maxLength=&quot;200&quot;
placeholder=&quot;Phone Number&quot;
required
/&gt;
&lt;/label&gt;
{isServerError ? (
&lt;p className=&quot;error&quot;&gt;Registration failed, please try again.&lt;/p&gt;
) : null}
&lt;button className=&quot;login-btn&quot;&gt;Register!&lt;/button&gt;
&lt;div className=&quot;divider&quot;&gt;
&lt;span className=&quot;divider-text&quot;&gt;or&lt;/span&gt;
&lt;/div&gt;
&lt;p&gt;Already have an account?&lt;/p&gt;
&lt;Link to=&quot;/login&quot; className=&quot;sign-up-btn&quot;&gt;
Login
&lt;/Link&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/div&gt;
);
};
export default RegisterPage;
import React, { useContext, useEffect} from &quot;react&quot;;
import { Link } from &quot;react-router-dom&quot;;
import AuthContext from &quot;../../context/AuthContext&quot;;
import useCustomForm from &quot;../../hooks/useCustomForm&quot;;
const RegisterPage = () =&gt; {
const { registerUser, isServerError } = useContext(AuthContext);
const [formData, handleInputChange, handleSubmit, reset] = useCustomForm(
{
firstName: &quot;&quot;,
lastName: &quot;&quot;,
username: &quot;&quot;,
email: &quot;&quot;,
address: &quot;&quot;,
phone_number: &quot;&quot;
},
registerUser
);
useEffect(() =&gt; {
if (isServerError) {
reset();
}
}, [isServerError, reset]);
return (
&lt;div className=&quot;lo-container&quot;&gt;
&lt;div className=&quot;logbanner&quot;&gt;&lt;/div&gt;
&lt;div className=&quot;login-form&quot;&gt;
&lt;form className=&quot;form&quot; onSubmit={handleSubmit}&gt;
&lt;h1&gt;New member setup an account&lt;/h1&gt;
&lt;div className=&quot;form-row&quot;&gt;&lt;/div&gt;
&lt;label className=&quot;form-label&quot;&gt;
&lt;input
type=&quot;text&quot;
name=&quot;firstName&quot;
value={formData.firstName || &quot;&quot;}
onChange={handleInputChange}
placeholder=&quot;First Name&quot;
required
/&gt;
&lt;/label&gt;
&lt;label className=&quot;form-label&quot;&gt;
&lt;input
type=&quot;text&quot;
name=&quot;lastName&quot;
value={formData.lastName || &quot;&quot;}
onChange={handleInputChange}
placeholder=&quot;Last Name&quot;
required
/&gt;
&lt;/label&gt;
&lt;label className=&quot;form-label&quot;&gt;
&lt;input
type=&quot;text&quot;
name=&quot;username&quot;
value={formData.username || &quot;&quot;}
onChange={handleInputChange}
placeholder=&quot;Username&quot;
required
/&gt;
&lt;/label&gt;
&lt;label className=&quot;form-label&quot;&gt;
&lt;input
type=&quot;password&quot;
name=&quot;password&quot;
value={formData.password || &quot;&quot;}
onChange={handleInputChange}
placeholder=&quot;Password&quot;
required
/&gt;
&lt;/label&gt;
&lt;label className=&quot;form-label&quot;&gt;
&lt;input
type=&quot;email&quot;
name=&quot;email&quot;
value={formData.email || &quot;&quot;}
onChange={handleInputChange}
placeholder=&quot;Email&quot;
required
/&gt;
&lt;/label&gt;
&lt;label className=&quot;form-label&quot;&gt;
&lt;input
type=&quot;text&quot;
name=&quot;address&quot;
value={formData.address || &quot;&quot;}
onChange={handleInputChange}
placeholder=&quot;Address&quot;
required
/&gt;
&lt;/label&gt;
&lt;label className=&quot;form-label&quot;&gt;
&lt;input
type=&quot;tel&quot;
name=&quot;phone_number&quot;
value={formData.phone_number || &quot;&quot;}
onChange={handleInputChange}
maxLength=&quot;200&quot;
placeholder=&quot;Phone Number&quot;
required
/&gt;
&lt;/label&gt;
{isServerError ? (
&lt;p className=&quot;error&quot;&gt;Registration failed, please try again.&lt;/p&gt;
) : null}
&lt;button className=&quot;login-btn&quot;&gt;Register!&lt;/button&gt;
&lt;div className=&quot;divider&quot;&gt;
&lt;span className=&quot;divider-text&quot;&gt;or&lt;/span&gt;
&lt;/div&gt;
&lt;p&gt;Already have an account?&lt;/p&gt;
&lt;Link to=&quot;/login&quot; className=&quot;sign-up-btn&quot;&gt;
Login
&lt;/Link&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/div&gt;
);
};
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 错误:

  1. formData 中,你有一个名为 phone_number 的字段,但在发送到服务器之前,你从 phone 中读取它,如果 phone 未定义并且服务器需要它,这可能导致错误的数据错误。
  2. 你的 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

  1. In formData you have a field named phone_number but before sending it to server, you are reading it from phone which might cause bad data error if phone is undefined and is required by server.
  2. 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.

huangapple
  • 本文由 发表于 2023年6月19日 10:03:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76503219.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定