javascript - 将数据从 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)并获取数据并显示它。任何想法?????
解决方案
您需要了解数据如何在 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')
});
推荐阅读
- python - 在 Windows 上接收时的 Digi-Xbee 数据包积压
- jenkins - 詹金斯为所有工作建立历史
- python - 使用 GridSearcCv 评估多个指标
- c# - 模型实体框架的动态映射表
- django - Django 在 IIS 10 中发送邮件
- c++ - 确定从yolov3 tiny到tensorflow lite的转换模型的输出张量
- ngrx - (nx) 特征库可以访问全局状态吗?
- macos - 使用 dnsmasq 从本地设备访问本地 dns
- python - 如何在 python 中获取声音文件(.wav)的时间长度?
- javascript - 模型方法是否忽略 Sequelize 中的级联?