我不能从客户端发送帖子请求!
我需要将中的HTTP请求发送到支付网关。Post请求需要有标题和主体有效负载。我有前端和后端分离,我使用Rest与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' });
}发布于 2021-02-04 16:07:02
有几种方法可以实现,比如提取,但是,我更喜欢使用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)
});发布于 2021-02-04 15:27:56
使用阿西克斯发送POST请求。容易多了。
const axios = require('axios')
let config = {
headers: {
header1: value,
}
}
let data = {
'amount': amount,
'id':id,
'currency':currency,
}
axios.post('https://payment....com/api-key/transaction', data,config)
.then(function (response) {
console.log(response);
})发布于 2021-02-04 15:28:14
您可以使用https://github.com/node-fetch/node-fetch
const fetch = require('node-fetch');
const body = {a: 1};
const response = await fetch('https://httpbin.org/post', {
method: 'post',
body: JSON.stringify(body),
headers: {'Content-Type': 'application/json'}
});
const data = await response.json();
console.log(data);https://stackoverflow.com/questions/66048463
复制相似问题