I am trying to develop a login system in my NextJS app. But I am keep getting the error –
AxiosError {message: ‘Request failed with status code 400’, name: ‘AxiosError’, code: ‘ERR_BAD_REQUEST’, config: {…}, request:
XMLHttpRequest, …}
Here, I am providing the neccessary code snippets related to this topic.
Client Side(RegisterPage) –
const [authState, setAuthState] = useState({
name: "",
email: "",
password: "",
password_confirmation: "",
});
const [loading, setLoading] = useState<boolean>(false);
const [errors, setErrors] = useState<registerErrorType>({});
const submitForm = () => {
setLoading(true);
axios
.post("http://localhost:3000/api/auth/register", authState)
.then((res) => {
setLoading(false);
const response = res?.data;
// debugger;
if (response?.status == 200) {
console.log("User created successfully");
} else if (response?.status == 400) {
setErrors(response?.errors);
}
})
.catch((error: any) => {
console.error("Axios request error:", error);
setLoading(false);
});
};
Server Side(RegisterPage) –
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const validator = vine.compile(registerSchema);
const output = await validator.validate(body);
validator.errorReporter = () => new ErrorReporter();
// check if email already existes
const user = await User.findOne({ email: output.email });
if (user) {
return NextResponse.json(
{
status: 400,
errors: {
email: "Email is already exists",
},
},
{ status: 200 }
);
} else {
// Encrypt the password
const salt = bcrypt.genSaltSync(10);
output.password = bcrypt.hashSync(output.password, salt);
await User.create(output);
return NextResponse.json(
{ status: 200, message: "User created successfully" },
{ status: 200 }
);
}
} catch (error) {
if (error instanceof errors.E_VALIDATION_ERROR) {
return NextResponse.json(
{ status: 400, errors: error.messages },
{ status: 400 }
);
}
}
}
Thank you 🙂
2
Answers
For this question, there are multiple answers. Have you checked these before? I think you may have to add the config with it. Adding some related links for your help.
1.https://stackoverflow.com/questions/72307388/axioserror-request-failed-with-status-code-400-in-react-js?rq=2,
2.https://stackoverflow.com/questions/44731340/getting-400-error-bad-request-using-axios,
3.https://stackoverflow.com/questions/73612522/react-upload-file-with-axios-gives-axioserror-code-err-bad-request?rq=2
Could it be that your authState input is simply wrong and being catched and throws a validation error? Can you do a console.log() or put a breakpoint on the authState body when it is sent to the server?
Also I would start by using a more general try-catch, right now you are using a specific catch on an error but only throw on a validation error (which seems to be what this is about) but what if it wasn’t, then the error would be swallowed and your code will crash.
Also, I know this doesn’t solve your specific problem in hand but in the grand scheme of things it might be worth considering going for a library like NextAuth or Auth0 to help you kick-start the authentication/authorisation work.
Hope this at leasts gives you something to think about 🙂