Todor Pavlovic
Todor Pavlovic

Reputation: 160

Send Post request in Node js Rest API

I CAN'T SEND POST REQUEST FROM CLIENT SIDE !

I need to send HTTP Post request in Node js Rest API to the payment gateway. Post request needs to have headers and body payload. I have frontend and backend separated, I'm using Rest API with express.js and payment gateway needs server to server communication so I can't to do that from client side. Basically when user clicks on payment I need to send call to my backend server then my backend server needs to send request to the payment gateway.

Payment gateway has documentation with only MVC ( Model View Controller ) and they really can't help.

So logic inside controller should be something like this

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' });
}

Upvotes: 0

Views: 9460

Answers (3)

Jesus Aguas
Jesus Aguas

Reputation: 244

There are several ways to do it, like Fetch, however, I prefer using 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)
      });

Upvotes: 3

pshenOk
pshenOk

Reputation: 526

You can use 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);

Upvotes: 0

Kashish Khullar
Kashish Khullar

Reputation: 424

Use Axios to send POST requests. Its much easier.

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);
  })

Upvotes: 3

Related Questions