If you want to call an external api in Sitecore JSS app, there are javascript libraries you can use. I will be using Axios in this demo.
Axios is a Javascript library which is used to make HTTP requests from node.js or XMLHttpRequests from the browser and it supports the Promise API that is native to JS ES6. It can be used intercept HTTP requests and responses and enables client-side protection against XSRF. It also has the ability to cancel requests.
Pre-requisites:
Create a sample JSS app with react template. You can refer https://sudhirkumarblogs155782548.wordpress.com/2021/04/26/how-to-create-an-app-using-sitecore-jss-and-run-in-disconnected-connected-integrated-mode/ to create it. Now let’s get started. Install Axios Library. Run below command npm install axios Create a component definition in Sitecore using the JSS CLI. Run below commandjss deploy component externalapicall –allowedPlaceholders jss-main
where externalapicall will be the component name
Implement the externalapicall react componentCreate the react component in src/components/externalapicall/index.js
Put below code in index.js created above.
import React from 'react'; import { Text, RichText } from '@sitecore-jss/sitecore-jss-react'; import { DataStore } from 'apollo-client/data/store'; const axios = require('axios'); const externalapicall = (props) => { // Create state variables let [responseData, setResponseData] = React.useState(''); let [studentname, setStudentName] = React.useState(''); let [message, setMessage] = React.useState(''); // fetches stock data based on parameters const fetchData = (e) => { e.preventDefault(); setMessage('Loading...'); axios .get('http://externalwebapi.local/api/values?name=' + studentname) .then(function (response) { // handle success setResponseData(response.data); setMessage(''); console.log(response); }) .catch(function (error) { // handle error console.log(error); setMessage(error); }) .then(function () { // always executed }); }; return ( <div style= > <h1 style= > Calling External Api </h1> <form onSubmit={fetchData}> <fieldset> <label htmlFor="studentname"> Enter name <input required name="studentname" id="studentname" type="text" placeholder="Name" value={studentname} onChange={(e) => setStudentName(e.target.value)} /> </label> <button type="submit">Submit</button> </fieldset> </form> <p>{message}</p> <h3>Name: {responseData ? responseData.name : ''}</h3> <p>Roll No: {responseData ? responseData.Roll : ''}</p> Courses: <ul> {responseData?.courses?.map((s) => ( <li key="s">{s}</li> ))} </ul> </div> ); }; export default externalapicall; Add the externalapi rendering to an app routeYou can use experience editor or content editor
Run the app in connected mode now.jss start:connected
While calling the external service I got below error
cors error in sitecore jss
To fix the issue you need to perform below
Install IIS CORS ModuleEnable itAdd configuration in web.config file.Install the IIS CORS Module Link to install the module – https://www.iis.net/downloads/microsoft/iis-cors-module
Update your web.config file of external api and add below section to appropriate location in web.config file. You need to specify the url of site which is trying to connect to the externalapi.
In my case its http://localhost:3000
<system.webServer> <cors enabled="true"> <add origin="http://localhost:3000"> <allowMethods> <add method="GET" /> <add method="HEAD" /> </allowMethods> </add> </cors> </system.webServer>Now you will be able to call external api successfully and get the expected response.
Now when you run your app in connected mode, you will see below screen
Add styling as per your needs and also you can run the app in integrated mode by publishing the app.
Happy Sitecoreing !! Thanks Sitecore