Expand my Community achievements bar.

Calling third party REST api call form clinet side on AEM (e.g. localhost:4052 )

Avatar

Level 2

Let's say we are calling an a third party API directly from React using axios/fetch. (localhost:9000)

To handle CORS issues we set proxy in  packege.json/webpack.config, and "passing relative URL" to axios/fetch(THIS WORKS!!)

NOW we deployed the same in AEM and hosting on localhost:4502.(THIS DOESN'T WORK)

I understand that now react build is deployed and proxy will not work in production, but I am looking for a way to handle it once it's deployed and served on AEM.

6 Replies

Avatar

Employee Advisor

Hi @chgovind ,

To make sure I am understanding the use case:

During development, you are using a webpack dev server and any calls to your external service you are using the Proxy features of the webpack dev server and thus passing in a relative URL. However, when you create your production build and deploy to AEM the JS is still passing in relative URLs to your 3rd party API?

You could look into using environment variables: Adding Custom Environment Variables · Create React App If you are in development mode you don't add a host name but in the production build you do append a host name to the 3rd party call...

Avatar

Level 2

You are close.

What if the third party API doesn't allow CORS.

Is there a way to handle this in Local AEM environment?

Avatar

Level 10

A better apprach to invoke a 3rd party endpoint - like a Restful service is to use an AEM service and write Java to invoke the service and then display the results in front end component. YOu should look at using HTL and Sling Models.

Avatar

Level 2

Yes that's a way but we are trying to make calls only from react client.

Avatar

Level 10

I would look at using Java on backend to invoke the 3rd party - as shown here where we invoke a Google Service and display the results in front end component -- Creating an Adobe Experience Manager 6.3 HTL Component that displays data from a Restful Web Service

Avatar

Level 10

Even in this write up - they suggest React alone - there is no way:

"React doesn't really have anything for consuming data"

Another way - is have React make a call to an AEM Sling Servlet - the servlet invokes a Java service (similar to the article i posted), gets the data and returns the data back to the React component --

Is it possible to consume a RESTful API with React.js alone (i.e. without any server-side language, ...