Access SharePoint from React app using sp-rest-proxy for development


Ahamed Fazil Buhari
Senior Developer
Published On :   26 Nov 2018
Visit Count
Today :  4    Total :   129



Hello everyone,

I wanted to publish this article in the very beginning of my other articles on React and Redux. In this article we will see how to connect to SharePoint environment from your react application during development. We use pnp-js to access SharePoint resource, but when it comes to development, we can’t deploy the solution to SharePoint every time to check its behavior and its very time consuming also. To avoid this, we use proxy which connects to SharePoint and we use this proxy in our react application (only for development purpose). Well, you can find the package from here sp-rest-proxy it is really well documented and it explains everything about installation and usage.

In this article, we will see how to give access SharePoint on-prem and SharePoint online (giving your organization proxy value in sp-rest-proxy settings to access Online)

Step 1: Clone and install the project from sp-rest-proxy.

clip_image002

Step 2: open command window from this location and run command npm run serve

It will ask for SharePoint URL and the credential (Here I am using SharePoint online). I am connecting through simple user credential

clip_image003

Once the authentication is successful, it will be connected to SharePoint with REST proxy through http://localhost:8080 and we need to use this proxy in our React app to access SP.

Step 3: I call this pnpConfig in App Constructor, since it could be the starting point of the app.

clip_image005

Step 4: Now we need export pnpConfig which gives url and headers that needed for REST call. Now your react app can access SP when you run in localhost

clip_image006

Step 5: To change SharePoint URL or to update Credentials, then go to the folder where sp-rest-proxy is installed and delete the file private.json inside config folder

clip_image008

And run the step 2 to give new URL or updated credentials.

If you get following error while accessing SharePoint online

Error: getaddrinfo ENOTFOUND login.microsoftonline.com login.microsoftonline.com:443

It mainly happens when you are behind firewall and need proxy to access internet (from your organization network). To overcome this issue, we need to add proxy url in server.ts file which is available in sp-rest-proxyclip_image010

And save server.ts file and run the Step2 again, this will solve proxy issue.

Happy Coding

Ahamed

Categories