I am not able to clearly Identify the bug, data is send in JSON Format still it is showing unusual error
Forgot Password Route
JavaScript
x
39
39
1
exports.forgotPassword = catchAsyncErrors(async (req, res, next) => {
2
const user = await User.findOne({ email: req.body.email });
3
4
if (!user) {
5
return next(new ErrorHandler("User not found", 404));
6
}
7
8
// Get ResetPassword Token
9
const resetToken = user.getResetPasswordToken();
10
11
await user.save({ validateBeforeSave: false });
12
13
const resetPasswordUrl = `${req.protocol}://${req.get(
14
"host"
15
)}/password/reset/${resetToken}`;
16
17
const message = `Your password reset token is :- nn ${resetPasswordUrl} nnIf you have not requested this email then, please ignore it.`;
18
19
try {
20
await sendEmail({
21
email: JSON.stringify(user.email),
22
subject: `Ecommerce Password Recovery`,
23
message
24
});
25
26
res.status(200).json({
27
success: true,
28
message: `Email sent to ${user.email} successfully`
29
});
30
} catch (error) {
31
user.resetPasswordToken = undefined;
32
user.resetPasswordExpire = undefined;
33
34
await user.save({ validateBeforeSave: false });
35
36
return next(new ErrorHandler(error.message, 500));
37
}
38
});
39
forgotPassword Action.js
JavaScript
1
25
25
1
export const forgotPassword = (email) => async(dispatch)=>{
2
try{
3
dispatch({type: FORGOT_PASSWORD_REQUEST});
4
5
const config = {headers : {"Content-Type": "application/json"}};
6
7
const {data} = await axios.post(
8
"/api/v1/password/forgot",
9
email,
10
config
11
);
12
13
dispatch({
14
type: FORGOT_PASSWORD_SUCCESS,
15
payload : data.message,
16
})
17
18
}catch(error) {
19
dispatch({
20
type: FORGOT_PASSWORD_FAIL,
21
payload: error.response.data.message,
22
});
23
}
24
}
25
As mentioned in some answers online available I have made few changes but Error is still their,
- In Action.js I have written content type as “application/json”.
- in forgotPassword Route while sending email to function, I have used a method JSON.stringify.
Advertisement
Answer
Your axios.post
statement sends a request whose body is an email address (i.e., plain text), but the Content-Type: application/json
wrongly claims it to be JSON. That leads to the observed error.
Correct would be
JavaScript
1
6
1
const data = await axios.post(
2
"/api/v1/password/forgot",
3
{email},
4
config
5
);
6
(Note the absence of braces around data
.)