在快递中回复两次

问题描述 投票:0回答:1

我的反应代码

<form action="/ContactUs/FormData" method="POST">
...         
</form>

handleSubmit(){
    fetch('/ContactUs/FormData')
    .then((results)=>results.json())
    .then((result)=>{
        if(result.name==='ErrorOccured'){
            this.setState({
                display: 'An Error Occured. Please try again!'
            });
        }
        else{
            this.setState({
                display: 'We have recorded your response '+result.name+ '. Please note your ID: '+ result.id
            });
        }
    })
}

我的快递代码

app.post("/ContactUs/FormData",function(req,res){

}
formResponse.save((err,data)=>{ 
    if(err){
        res.write(JSON.stringify({"name":"ErrorOccured"}));
    }
    else{
        res.write(JSON.stringify(data));
    }
    res.redirect("/ContactUs");
});

我希望当数据提交到'/ Contact Us / Form Data'时,应该使用Mongoose保存,然后应该呈现表单页面(一个post方法中有两个响应请求)。

我如何实现这一点,即页面也被渲染,一些json数据也被发送到React。

javascript node.js reactjs express mongoose
1个回答
0
投票

Express不应该呈现表单页面。 ReactJS应该。 Express必须回复React渲染表单页面所需的任何数据。

您的方案应该是:

  1. React发送表单数据
  2. Express将其保存到数据库中
  3. 保存后,检索呈现表单页面所需的任何数据
  4. 在express中,将表单页面的数据和保存操作中的成功/错误消息组合到一个JS对象中。
  5. Express应该通过res.write将此单个对象发送到React(无重定向)
  6. React通过显示Express发送的数据来读取答案,显示任何错误消息和/或呈现表单页面

请注意,Express可以返回任何类型的数据,包含React的信息以了解接下来要呈现的页面。

© www.soinside.com 2019 - 2024. All rights reserved.