Home > front end >  PayFast integration in NodeJS / ReactJS
PayFast integration in NodeJS / ReactJS

Time:04-03

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?

CodePudding user response:

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

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

CodePudding user response:

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.

  • Related