koltyakov / sp-rest-proxy

🌐 SharePoint API Proxy for local development
MIT License
172 stars 43 forks source link

Add end-to-end example for create-react-app #32

Closed koltyakov closed 7 years ago

koltyakov commented 7 years ago

1. Create React app && navigate to it:

create-react-app my-app && cd my-app

2. Install sp-rest-proxy and concurrently dependency:

npm install sp-rest-proxy concurrently --save-dev

or using yarn:

yarn add sp-rest-proxy concurrently --dev

3. Add scripts to package.json:

{
  "scripts": {
    ...
    "proxy": "node ./api-server.js",
    "startServers": "concurrently --kill-others \"npm run proxy\" \"npm run start\""
    ...
  }
}

Script names can be as one wish. npm run start stands for react app serve.

4. Add API proxy setting into package.json:

{
  "proxy": "http://localhost:8081"
}

This is the address which corresponds to sp-rest-proxy startup settings.

5. Create proxy server script, e.g. ./api-server.js:

const RestProxy = require('sp-rest-proxy');

const settings = {
  port: 8081
};

const restProxy = new RestProxy(settings);
restProxy.serve();

6. Configure sp-rest-proxy:

6.1. Run:

npm run proxy

6.2. and provide SharePoint connection options.

By default, ./config/private.json is created. It's good to add config/private.json to .gitignore to avoid unnecessary saving of the private options to a git repository.

6.3. Check if credentials are correct by navigating to http://localhost:8081 and executing any REST request, e.g. /_api/web. On success, some data should be responded from SharePoint API.

Stop sp-rest-proxy, Ctrl+C in a console.

7. Start local development serve:

npm run startServers

Now when both servers have been started your React app can request for SharePoint API as if it were already deployed to SharePoint page, WebPack proxies local API requests to sp-rest-proxy and then requests to real SharePoint instance.

E.g., if open http://localhost:3000 in a browser and run:

fetch(`/_api/web`, {
    accept: 'application/json;odata=verbose',
})
  .then(r => r.json())
  .then(console.log)
  .catch(console.log);

Data from SharePoint is here on the page!

Black magic! Happy codding!

koltyakov commented 7 years ago

Wrapped this as an article here.

kayodebristol commented 7 years ago

OMG, That's awesome! Sorry, I've been going the long way around, trying to reverse engineer react-scripts and webpack. Found the proxy setting on my own... then started scratching my head again. I'll try your end-to-end solution in the morning and provide feedback. So many thanks!

kayodebristol commented 7 years ago

Couldn't sleep. It works! It's beautiful. It's gonna save a huge amount of dev time. Thanks again.