首页 > 解决方案 > 将数据从 Node 服务器重定向并发送回 React

问题描述

我有一个 NodeJS 服务器,我在其中使用 Express 和一个带有 React 的前端。我想知道如何将数据从服务器发送到前端。我见过的所有解决方案都使用来自前端的调用,然后服务器应答,最后前端获取数据。我的问题是我没有来自前端的呼叫,而是呼叫后端 (router.get('/callback')) 到后端 (router.get('/receipt/:id' ))。这是更好理解的代码。


router.get('/callback', (req,res) => {

    const ref = req.query.reference;

    verifyPayment(ref, (error,body)=>{
        if(error){
            //handle errors appropriately
            console.log(error)
            return res.redirect('/payment/error');
        }
        response = JSON.parse(body);   

        const data = _.at(response.data, ['reference', 'amount','customer.email', 'metadata.full_name']);

        [reference, amount, email, full_name] =  data;

        newDonor = {reference, amount, email, full_name};

        const donor = new Donor(newDonor);

        donor.save().then((donor)=>{
            console.log("--------------- donor" + donor);
            if(!donor){
                return res.redirect('/payment/error');
            }
            res.redirect('/payment/receipt/' + donor._id);
        }).catch((e)=>{
            res.redirect('/payment/error');
        });
    });
});

router.get('/receipt/:id', (req, res)=>{

    const id = req.params.id;

    Donor.findById(id).then((donor)=>{
        if(!donor){    
            res.redirect('/payment/error')
        }

        // I'VE TRIED THIS
        //res.redirect('http://localhost:3000/#' + donor.full_name);

        /*
        AND THIS
        console.log(donor.full_name);
        const resp = axios.post('http://localhost:3000', {params: {donor.full_name}});
        console.log(resp.data);
        */
    }).catch((e)=>{
        res.redirect('/payment/error')
    });

});


现在我想要回到前端(使用 React 的 index.js)并获取数据并显示它。任何想法?????

标签: javascriptnode.jsreactjs

解决方案


您需要了解数据如何在 Node 服务器和您的 React 应用程序之间传递。我们使用 JSON 对象将数据服务器传递给客户端(查找 REST API 以获取更多信息)

在你的服务器上试试这个

router.get('/receipt/:id', (req, res)=>{

    const id = req.params.id;

    Donor.findById(id).then((donor)=>{
        if(!donor){    
            res.redirect('/payment/error')
        }

      //How to send the data
      res.status(200).json({
      message: "Data returned Successfully",
      Fullname:"donor.full_name"
    });

    }).catch((e)=>{
        res.redirect('/payment/error')
    });

推荐阅读