I send a error from backend if a certain condition is matched, now like this I have send multiple errors at multiple situations, so I need to get the message that I send from the backend (node, express), I used axios in frontend (react), but I am getting a html doc which contains the message, but I want only the message.
This is what I tried:
const Login = () => {
const [formData, setFormData] = useState();
const handleLoginUser = async () => {
try {
const res = await axios.post("/api/v1/user/login", {
username: formData?.username,
password: formData?.password,
});
} catch (error) {
console.log("Error is this", error.response.data);
}
};
Error is this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Error: Please provide username and password<br> at file:///C:/Users/gurki/Desktop/github-projects/Mern-quiz/Backend/src/Controllers/user.controller.js:49:11<br> at file:///C:/Users/gurki/Desktop/github-projects/Mern-quiz/Backend/src/Utils/asyncHandler.js:3:21<br> at Layer.handle [as handle_request] (C:UsersgurkiDesktopgithub-projectsMern-quizBackendnode_modulesexpresslibrouterlayer.js:95:5)<br> at next (C:UsersgurkiDesktopgithub-projectsMern-quizBackendnode_modulesexpresslibrouterroute.js:149:13)<br> at Route.dispatch (C:UsersgurkiDesktopgithub-projectsMern-quizBackendnode_modulesexpresslibrouterroute.js:119:3)<br> at Layer.handle [as handle_request] (C:UsersgurkiDesktopgithub-projectsMern-quizBackendnode_modulesexpresslibrouterlayer.js:95:5)<br> at C:UsersgurkiDesktopgithub-projectsMern-quizBackendnode_modulesexpresslibrouterindex.js:284:15<br> at Function.process_params (C:UsersgurkiDesktopgithub-projectsMern-quizBackendnode_modulesexpresslibrouterindex.js:346:12)<br> at next (C:UsersgurkiDesktopgithub-projectsMern-quizBackendnode_modulesexpresslibrouterindex.js:280:10)<br> at Function.handle (C:UsersgurkiDesktopgithub-projectsMern-quizBackendnode_modulesexpresslibrouterindex.js:175:3)</pre>
</body>
This is the error.
I want only Error message
Backend code:
export const loginUser = asyncHandler(async (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
throw new ApiError(400, "Please provide username and password");
}
if (!(await User.findOne({ username }))) {
throw new ApiError(401, "User does not exist");
}
const user = await User.findOne({ username });
if (!(await user.checkPassword(password))) {
throw new ApiError(401, "Incorrect password");
}
This is not the complete code,just giving the hint.
2
Answers
did you check cors policy error?, if havent cors lib., you must install cors library
I’m not sure what
ApiError
is in your code but throwing new error is not correct.the correct way is:
with this you can get both message and staus code on front side.