在我正在收集邮箱中的忘记密码文件中,我必须向其中发送恢复链接.我收到了作为输入的邮箱,并执行了sole.log向我显示了我收到的邮箱. 接下来,我发送了邮件,并将邮件发送到后端以生成恢复链接,但在后端,它显示链接未定义,我也不知道背后的原因.如果有人能帮忙,我会非常感激的.

这就是被遗忘的密码zoom 器

export const forgotPasswordReducer = (state={},action) => {
  switch(action.type){
    case FORGOT_PASSWORD_REQUEST:
    case RESET_PASSWORD_REQUEST:
      return {
        loading:true,
        ...state,
        error:null,
      }
    case FORGOT_PASSWORD_SUCCESS:
      return{
        ...state,
        loading:false,
        message:action.payload,
      };
    case RESET_PASSWORD_SUCCESS:
      return {
        ...state,
        loading:false,
        success:action.payload,
      };
    case FORGOT_PASSWORD_FAIL:
    case RESET_PASSWORD_FAIL:
      return{
        ...state,
        loading:false,
        error:action.payload,
      };
    case CLEAR_ERRORS:
      return {
        ...state,
        error:null,
      }
    default:
      return state;
  }
}

这是忘记密码操作

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,
        })
    }
}

这是我从用户那里接受邮箱输入的文件

import React, { Fragment , useState, useEffect} from 'react'
import "./ForgotPassword.css";
import MailOutLineIcon from "@material-ui/icons/MailOutline";
import MetaData from "../layout/MetaData";
import Loader from "../layout/Loader/Loader.js";
import {useDispatch,useSelector} from "react-redux";
import {useAlert} from "react-alert";
import {clearErrors,forgotPassword} from "../../actions/userActions";

const ForgotPassword = () => {
    const dispatch = useDispatch();
    const alert = useAlert();
    const {error,message,loading} = useSelector((state)=>state.forgotPassword);
    const [email,setEmail] = useState("");

    const forgotPasswordSubmit = (e) => {
        e.preventDefault();
        const myForm = new FormData();
        myForm.set("email",email);
        dispatch(forgotPassword(myForm));
    };

    useEffect(()=>{
        if(error){
            alert.error(error);
            dispatch(clearErrors());
        }
        if(message){
            alert.success(message);
        }
    },[dispatch,error,alert,message]);

  return (
    <Fragment>
        {loading?(
        <Loader/>
    ):
    (
    <Fragment>
        <MetaData title="Forgot Password"/>
        <div className="forgotPasswordContainer">
            <div className="forgotPasswordBox">
                <h2 className="forgotPasswordHeading">Forgot Password</h2>
                <form className="forgotPasswordForm" onSubmit={forgotPasswordSubmit}>
                    <div className="forgotPasswordSubmit">
                        <MailOutLineIcon/>
                        <input type="email" placeholder="Email" required name="email" value={email} onChange={(e)=>setEmail(e.target.value)}/>
                    </div>
                    <input type="submit"
                    value="Send"
                    className="forgotPasswordBtn"/>
                </form>
            </div>
        </div>
    </Fragment>) }
    </Fragment>
  )
}

export default ForgotPassword;

这是后端的用户控制器文件

在这里,当我try sole.log req.body.mail时,我得到了未知的定义.

exports.forgotPassword = catchAsyncErrors(async(req,res,next)=>{
    console.log(req.body.email);
    const user = await User.findOne({email:req.body.email});
     
    if(!user){
        return next(new ErrorHandler("User not found",404));
    }

    // get reset password token 

    const resetToken = user.getResetPasswordToken();

    // saving the user to save the token of the user that was generated

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

    const resetPasswordUrl = `${req.protocol}://${req.get('host')}/api/v1/password/reset/${resetToken}`

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

    try{    

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

        res.status(200).json({
            success:true,
            message:`Email was sent to ${user.email} successfully`,
        });

    }
    catch(error){
        // if their is some kind of error we would remove the token that was generated and also 
        // make the expire time of the token to be the current time.
        user.resetPasswordToken = undefined;
        user.resetPasswordExpire = undefined;
        await user.save({validateBeforeSave:false});
        return next(new ErrorHandler(error.message,500));
    }
});


有没有人能帮我弄清楚为什么会这样.如果需要更多的代码片段或文件来解决这个错误,请让我知道我也会附上它们.

试图弄清楚为什么在从表单中以reaction-redux形式输入数据后,数据没有被传递.它表明,作为输入的邮箱是未定义的,我也找不出背后的原因.

推荐答案

您正在将表单数据传递给forgotPassword操作,该操作通过axios发出POST请求.但是,对于axios,您已经指定要传递JSON数据.

const config = {
  headers: {
    "Content-Type": "application/json" // <-- JSON data
  }
};
        
const { data } = await axios.post("/api/v1/password/forgot", email, config);

could使用"Content-Type": "multipart/form-data"来发送表单数据,但后端也需要配置为接收这种类型的请求正文.

不过,听起来您的后端只是在等待JSON数据.您可以不传递FormData对象,而是传递一个Java脚本对象,并让axios处理将Body有效负载串行化的JSON.

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

    const config = {
      headers: {
        "Content-Type": "application/json"
      }
    };
        
    const { data } = await axios.post("/api/v1/password/forgot", body, config);

    dispatch({
      type: FORGOT_PASSWORD_SUCCESS,
      payload: data.message,
    });
  } catch(error) {
    dispatch({
      type: FORGOT_PASSWORD_FAIL,
      payload: error.response.data.message,
    });
  }
};
const forgotPasswordSubmit = (e) => {
  e.preventDefault();
  dispatch(forgotPassword({ email }));
};

Reactjs相关问答推荐

如何使用mui为可重复使用的react 按钮应用不同的风格

父组件更新后不重新呈现子组件

如何将图像(在代码中称为自己)定位在蓝色圈内的点上?我正在使用material UI和Reaction

是否为Reaction中未使用的组件生成Tailwincss样式?

如何在物料界面react 的多选菜单中设置最大 Select 数限制

关于forwardRef,我可以';我不理解第二个用例

获取类别和页面的参数

React Todo List 应用程序我在实现删除功能时遇到问题

从 MongoDB createAt 字段中分割精确时间

Mui Datepicker 设置了错误的日期

我可以同时使用 Gatsby 和 NEXT.JS 吗?

useRef 不关注模态

从ReactDataGridtry 将数据传递给父组件

React Js和Firestore中如何将当前ID与集合中的ID查询以仅显示具有相似字段和值的文档-第二部分

自动重新获取不起作用 - RTK 查询

Cypress - 替换 React 项目中的变量

React Router v6 - 访问嵌套路由和处理手写 url 的正确方法

在react 路由dom版本6中的组件内添加路由

useEffect 仅在跟随链接后有效,不适用于直接链接

如何在 React x 中返回组件?