Skip to content
Advertisement

SyntaxError: Unexpected token ” in JSON at position 0 at JSON.parse

I am not able to clearly Identify the bug, data is send in JSON Format still it is showing unusual error

Forgot Password Route

exports.forgotPassword = catchAsyncErrors(async (req, res, next) => {
  const user = await User.findOne({ email: req.body.email });

  if (!user) {
    return next(new ErrorHandler("User not found", 404));
  }

  // Get ResetPassword Token
  const resetToken = user.getResetPasswordToken();

  await user.save({ validateBeforeSave: false });

  const resetPasswordUrl = `${req.protocol}://${req.get(
    "host"
  )}/password/reset/${resetToken}`;

  const message = `Your password reset token is :- nn ${resetPasswordUrl} nnIf you have not requested this email then, please ignore it.`;

  try {
    await sendEmail({
      email: JSON.stringify(user.email),
      subject: `Ecommerce Password Recovery`,
      message
    });

    res.status(200).json({
      success: true,
      message: `Email sent to ${user.email} successfully`
    });
  } catch (error) {
    user.resetPasswordToken = undefined;
    user.resetPasswordExpire = undefined;

    await user.save({ validateBeforeSave: false });

    return next(new ErrorHandler(error.message, 500));
  }
});

forgotPassword Action.js

export const forgotPassword = (email) => async(dispatch)=>{
    try{
        dispatch({type: FORGOT_PASSWORD_REQUEST});

        const config = {headers : {"Content-Type": "application/json"}};

        const {data} = await axios.post(
            "/api/v1/password/forgot",
            email,
            config
        );

        dispatch({
            type: FORGOT_PASSWORD_SUCCESS,
            payload : data.message,
        })

    }catch(error) {
        dispatch({
            type: FORGOT_PASSWORD_FAIL,
            payload: error.response.data.message,
        });
    }
}

As mentioned in some answers online available I have made few changes but Error is still their,

  1. In Action.js I have written content type as “application/json”.
  2. 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

const data = await axios.post(
  "/api/v1/password/forgot",
  {email},
  config
);

(Note the absence of braces around data.)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement