PayFast integration in NodeJS / ReactJS

866 Views Asked by At

I am trying to integrate PayFast into my React / NodeJS app. Using Express, my NodeJS successfully retrieves a payment uuid from the PayFast endpoint (I see this uuid in my console log) -

app.get("/api", async (req, res) => {

    paymentData["signature"] = generateSignature(paymentData, phrase);
    console.log(paymentData["signature"])

    const str = dataToString(paymentData)
    const id = await getPaymentId(str)
    res.json({uuid: id})
})

However, in my front end (ReactJS) I am getting an undefined response & possible CORS issue from my backend API end point when trying to retrieve this uuid -

My custom fetch hook:

export default function useFetch(baseUrl) {
  const [loading, setLoading] = useState(true);

  function get() {
    return new Promise((resolve, reject) => {

      fetch(baseUrl)
        .then(res => {
            console.log(res)
            res.json()
        })
        .then(data => {
          console.log(data);
          if (!data) {
            setLoading(false);
            return reject(data);
          }
          setLoading(false);
          
          resolve(data);
        })
        .catch(error => {
          setLoading(false);
          reject(error);
        });
    });
  }

  return { get, loading };
};

The error:

Response {type: 'cors', url: 'http://localhost:3001/api', redirected: false, status: 200, ok: true, …}
undefined

If I test my NodeJS end point from my browser, it successfully comes back with my payment uuid. Any one have any ideas why my React app is acting up?

3

There are 3 best solutions below

0
On

For those others who might encounter a similar type of an issue, I have attached a blog post with the method that I have used to solve the CORS issue, as well as integrate with the PayFast API.

https://codersconcepts.blogspot.com/2022/04/nodejs-payfast-integration.html

3
On

Update your CORS config to accept connections from the React app host.

app.use(cors({
  origin: 'http://localhost:3000',
}));
4
On

Open package.json of your react app and add a line on the bottom of the json file:

"proxy":"http://localhost:3001"

3001 is the PORT that your Node http server is running on locally, if it's another PORT just change it accordingly. This will redirect all http traffic from your webpack dev server running on PORT 3000, to your Node server running on 3001.