I have a simple login route in express:
//login
router.post('/login',async (req,res) => {
try{
const user = await User.findOne({username: req.body.username});
console.log(user);
if (!user) {
return res.status(400).json({
success: false,
message: "username not found"
});
}
const validated = await bcrypt.compare(req.body.password,user.password);
if (!validated) {
console.log('password is wrong')
return res.status(400).json({
success: false,
message: "password not found"
})
}
const {password,...others} = user._doc;
res.status(200).json(others,{
success: true,
});
}
catch(err){
res.status(500).json(err);
}
})
I am using react for my frontend and axios to make requests:
const handleSubmit = async (e) => {
e.preventDefault();
dispatch({type: 'LOGIN_START'});
try{
const res = await axios.post('http://localhost:5000/api/auth/login',{
username: userRef.current.value, //add the body
password: passwordRef.current.value
})
if (res.data.success) {
dispatch({type: "LOGIN_SUCCESS",payload: res.data})//if everything is fine save it into the localstorage.
}
console.log(res,"something went wrong")
}
catch(err) {
dispatch({type: "LOGIN_FAILURE"})
}
}
Now the problem is whenever i sent a status code of 400 it doesn't log the response which i want to see if i want to let the user know what's going on.
It just logs:
xhr.js:184 POST http://localhost:5000/api/auth/login 400 (Bad Request)
I want to see the content the json i am sending back.
I didn't find any similar answers regarding this.
What am i missing?
Axios 400 Bad request , you could console.log(err.response) in your catch block to get a more human-readable object.
axios errors come in three types: message, request and response.
catch(err) {
console.log(err.response);
dispatch({type: "LOGIN_FAILURE"})
}
Related
I am not getting status message as 500 eventhough I set. always getting status message as 200. how to set the status as 500?
here is my code : "express": "4.17.2",
router.post('/register', async (req: Request, res: Response) => {
const { password, email } = req.body;
try {
const isUserExist = await UserModel.findOne({ email: email });
if (isUserExist) {
//status not set.
return res.json({ message: 'User already exist', success: false }).status(500);
}
const hashPassword = bcrypt.hashSync(password, 10);
req.body.password = hashPassword;
const newUser = new UserModel(req.body);
await newUser.save();
res.json({ message: 'user created successfully', success: true });
} catch (error) {
res.sendStatus(500).json({ message: 'Error creating user', success: false });
}
});
react axios:
when i use:
return res.status(500).json({ message: 'User already exist', success: false }); getting something went wrong
export const registerUser = createAsyncThunk('post/user', async (user: RegisterFormProps) => {
try {
const response = await axios.post(environment.BASE_URL + '/user/register', user);
console.log('suc', response.data.success);
if (response.data.success) {
toast.success(response.data.message);
} else {
toast.error(response.data.message);
}
} catch (error) {
const err = error as AxiosError;
console.log('err', err);
toast.error('something went wrong');
}
});
You should be using res.status instead of res.sendStatus in your code.
res.status(statusCode) just sets the status on the response.
whereas res.sendStatus(statusCode) sends the response after setting the status.
for example:
res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')
on the client side try using error.response.data in your catch block
Try this one:
router.post('/register', async (req: Request, res: Response) => {
const { password, email } = req.body;
try {
const isUserExist = await UserModel.findOne({ email: email });
if (isUserExist) {
//status not set.
return res.status(500).json({ message: 'User already exist', success: false });
}
const hashPassword = bcrypt.hashSync(password, 10);
req.body.password = hashPassword;
const newUser = new UserModel(req.body);
await newUser.save();
res.status(201).json({ message: 'user created successfully', success: true });
} catch (error) {
res.status(500).json({ message: 'Error creating user', success: false });
}
});
I am new to async/await so I have an exercise like below code, I have converted this code to async/await many times and still no success. Please help me. Thanks very much!
My code is as follows:
exports.register = (req, res) => {
const user = req.body;
try {
// Validate the registration form
validateRegisterForm(user)
.then((response) => {
// If response is true, hash the password
if (response) {
Md5Password(user.password)
.then(async (hash) => {
const { name, email } = user;
const newUser = new User({
name,
password: hash,
});
// Save the user
const savedUser = await newUser.save();
res.status(200).json(savedUser);
})
.catch((error) => {
res.status(500).json({
message: error.message,
err: "500: Internal Server Error",
});
});
}
// But if response is false, show the error message
else {
res.status(401).json({
message: errorMessage(),
error: "401: Unauthorized",
});
}
})
.catch((error) => {
res.status(500).json({
message: error.message,
err: "500: Internal Server Error",
});
});
} catch (error) {
res.status(500).json({
error: error.message,
message: "registration failed",
e: "500: Internal Server Error",
});
}
};
Please help me, thanks a lot!
Not sure exactly what you're trying to achieve, but here's a version of your code with async/await:
exports.register = async (req, res) => {
const user = req.body;
try {
// Validate the registration form
const response = await validateRegisterForm(user);
// If response is true, hash the password
if (response) {
const hash = await Md5Password(user.password);
const { name, email } = user;
const newUser = new User({
name,
password: hash,
});
// Save the user
const savedUser = await newUser.save();
res.status(200).json(savedUser);
} else {
res.status(401).json({
message: errorMessage(),
error: "401: Unauthorized"
});
}
} catch (e) {
res.status(500).json({
message: e.message,
err: "500: Internal Server Error"
});
}
}
I have this simple post method in back-end:
router.post('/users', async function(request, response) {
try {
const userToRegister = request.body;
const user = await CreateUserService.execute(userToRegister);
return response.json(user);
} catch (err) {
console.log(err);
return response.status(401).json({ message: 'email already registered' });
}
});
At the front end i'm trying to catch the response if the users is already registered, like this:
api.post('users', user.userFields)
.then(response => {
console.log(response)
})
.catch(err => {
console.log(err);
})
In this case, response is always undefined.
If a pass return response.json(err); in backend it works fine.
What am i missing here?
Nevermind guys, found error.
My fail was in the user catch block of CreateUserService.
I am a begginer in developing full stack applications. I'm currently building a React, Node and Express.js application where users login. I have error checking in the backend side and I want to show it on the client side.
here's my Node Code:
app.post("/api/login",async(req,res)=>{
try {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(404).send({ message: "No user with that email" });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(401).send({ message: "Passwords do not match" });
}
res.send(user);
} catch (error) {
res.status(500).send(error);
}
})
I'm using redux actions to make the request
here's my React Code:
export const logIn = credentials => async dispatch => {
try {
const res = await axios.post("/api/login", credentials);
console.log(res.data);
dispatch({
type: LOG_IN,
payload: res.data
});
} catch (error) {
dispatch({ type: LOG_IN_FAILED });
console.log(error);
}
};
When I console.log the error.message, I'm getting Request failed with status code 404 Instead of the error message e.g { message: "No user with that email" }.But when I make the request with postman, I'm getting the error message { message: "No user with that email" }.Is there a way I can show that on my client side? Because error.message doesnot seem to work
I found the error object on the error.response.data which contained the actual error from my backend which was { message: "No user with that email" } so the code would look like this:
export const logIn = credentials => async dispatch => {
try {
//make request to backend (with axios in my case)
} catch ({reponse}) {
dispatch({ type: LOG_IN_FAILED });
console.log(response.data); //find the error object from the backend incase of an error
}
};
For more info, check out https://github.com/axios/axios/issues/960
After making request to the server, am getting net::ERR_TOO_MANY_REDIRECTS. This was working earlier, now the App cant make any request to the server.
Though the API's are working when tested with Postman.
This is the action that makes the request to the server
//Login User
export const login = (email, password) => async (dispatch) => {
const config = {
headers: {
"Content-Type": "application/json",
},
};
const body = JSON.stringify({ email, password });
console.log(email, password); //This is where the run time stops and catch error
try {
const res = await axios.post(authLogin, body, config);
console.log(res);
dispatch({
type: LOGIN_SUCCESS,
payload: res.data,
});
dispatch(loadUser());
} catch (err) {
const errors = err.response.data.errors;
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, "danger")));
}
dispatch({
type: LOGIN_FAIL,
});
}
};
This is the controller for the API that's been called
// #route POST api/auth/login
// #desc Login user and return JWT token
// #access Public
const loginUser = async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
try {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user)
return res.status(401).json({
errors: [
{
msg:
"The email address " +
email +
" is not associated with any account. Double-check your email address and try again.",
},
],
});
//validate password
if (!user.comparePassword(password))
return res
.status(401)
.json({ errors: [{ msg: "Invalid email or password" }] });
// Make sure the user has been verified
if (!user.isVerified)
return res.status(401).json({
errors: [
{
type: "not-verified",
message: "Your account has not been verified.",
},
],
});
// Login successful, write token, and send back user
res.status(200).json({ token: user.generateJWT() });
} catch (error) {
console.error(error.message);
res
.status(500)
.json({ errors: [{ msg: "Server unavailable, try again latter" }] });
}
};
This is a react, node.js, mongoDB and Redux project. Have not experience this before.
Kindly help if you have any idea what i did wrong.
Thanks.
Resolved. It turns out that the SSL-VPN i was using on my machine caused the issue. All the APIs started working immediately i disconnected the VPN.