我无法从客户端发送 POST 请求!
我需要将 Node js Rest API 中的 HTTP Post 请求发送到支付网关。发布请求需要具有标头和正文有效负载。我将前端和后端分开,我将 Rest API 与 express.js 一起使用,并且支付网关需要服务器到服务器的通信,因此我无法从客户端执行此操作。基本上,当用户点击支付时,我需要向我的后端服务器发送呼叫,然后我的后端服务器需要向支付网关发送请求。
支付网关只有 MVC(模型视图控制器)的文档,他们真的无能为力。
所以控制器内部的逻辑应该是这样的
exports.payment = (req, res, next) => {
const { amount, id, currency } = req.body;
//add headers
//create body paloyad
//send request to https://payment....com/api-key/transaction
//receive response
res.status(200).json({ status: 'success' });
}
有几种方法可以做到,比如 Fetch,但是,我更喜欢使用Axios:
const axios = require('axios');
exports.payment = (req, res, next) => {
const { amount, id, currency } = req.body;
//add headers
const options = {
headers: {'X-Custom-Header': 'value'}
};
//create body payload
const body = {
amount: amount
id: id
currency: currency
};
//send request to https://payment....com/api-key/transaction
axios.post('https://payment....com/api-key/transaction', body, options)
.then((response) => {
//receive response
console.log(response);
res.status(200).json({ status: 'success' });
})
.catch((error) => {
console.log(error)
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句