I created a Backend server and posted it to Heroku and now I am using the server URL to post and get data from it. However when I display an error message it's getting me the status code instead of the actual error.
My Backend login code.
export const loginUser = asyncHandler(async(req, res) => {
const { email, password } = req.body;
const user = await userModel.findOne({ email });
const token = generateToken(user._id)
if(user && (await user.matchPassword(password))){
res.json({
_id:user._id,
username: user.username,
email: user.email,
profilePic:user.profilePic,
admin:user.admin,
token:token,
});
} else {
res.status(400)
throw new Error("invalid email or password please check and try again!");
}
});
My user Actions code since I am suing redux
export const login = (email, password) => async (dispatch) => {
try {
dispatch({
type: USER_LOGIN_REQUEST,
});
const url = `${process.env.REACT_APP_SERVER_URL}api/loginuser`;
const config = {
headers: {
"Content-type": "application/json",
},
};
const { data } = await axios.post(
url,
{
email,
password,
},
config
);
dispatch({
type: USER_LOGIN_SUCCESS,
payload: data,
});
localStorage.setItem("userInfo", JSON.stringify(data));
} catch (error) {
dispatch({
type: USER_LOGIN_FAIL,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.message,
});
}
};
CodePudding user response:
First you need to send an error message from your Back End like so :
export const loginUser = asyncHandler(async(req, res) => {
const { email, password } = req.body;
const user = await userModel.findOne({ email });
const token = generateToken(user._id)
if(user && (await user.matchPassword(password))){
res.json({
_id:user._id,
username: user.username,
email: user.email,
profilePic:user.profilePic,
admin:user.admin,
token:token,
});
} else {
res.status(400).json({errorMessage :"invalid email or password please check and try again!" })
}
});
Then get it in the React part (make sure to read the comment I added after that console.log
):
export const login = (email, password) => async (dispatch) => {
try {
dispatch({
type: USER_LOGIN_REQUEST,
});
const url = `${process.env.REACT_APP_SERVER_URL}api/loginuser`;
const config = {
headers: {
"Content-type": "application/json",
},
};
const { data } = await axios.post(
url,
{
email,
password,
},
config
);
dispatch({
type: USER_LOGIN_SUCCESS,
payload: data,
});
localStorage.setItem("userInfo", JSON.stringify(data));
} catch (error) {
console.log(error); // look at the console, as I may miss the correct retuned error object
dispatch({
type: USER_LOGIN_FAIL,
payload:
error.response.data.errorMessage
});
}
};
CodePudding user response:
you need to return response instead of throwing the error:
res.status(400)
res.json({
message: "invalid email or password please check and try again!"
});