在 Node js Rest API 中发送 Post 请求

托多·帕夫洛维奇

我无法从客户端发送 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在POST方法的REST API中发送日期

读取超时。向node.js API发送POST请求时出错

如何在Go中发送POST请求?

如何在node.js中发出HTTP POST请求?

通过Rest API使用Javascript发送Http POST请求

用于在Node.js中发送邮件的Gmail API

Node.js发送外部API POST请求

如何在node.js中发送带有数据和承载授权的POST请求?

Django Rest API验证请求中发送的数据

通过Observable从Angular发送POST请求到Node.js

在使用node.js中的REST API时请求参数

在AJAX POST请求中发送通过JS处理的图像

在android studio中发送POST请求

如何通过ID,node.js在rest API中发送多个帖子请求?

通过Node.js中的AWS Lambda发送POST请求

如何在Node JS中发送POST请求的Content-Type:application / octet-stream文件

React.js,Node.js:在React中发送axios请求

(仅限Safari)Axios请求不会将cookie发送到Node.js / Express REST API

在node.js中发送带有XML数据的POST请求:错误400,“客户端发送的请求在语法上不正确”

在next.js中发送对Api的发布请求

每当在Node.js API中发出GET请求时,如何发送随机集合?

Node.js请求模块....在主体中发送JSON以使用api请求进行API请求

Node.js:系统发送两次POST请求

在Firefox插件中发送POST请求(javascript)

击中发送“请求正文”的REST Controller POST方法时,获取“格式错误的语法”

使用 Node Js 和 express 调用来自 rest api 的 post 请求时出错。请求数据变空

在java中发送JSON Post HTTP请求

在 Node js 中 Rest Api 请求(curl 到 Node.js,python 到 Node.js)

使用 $.ajax() 在 JSON 中发送 POST 请求