koltyakov / sp-rest-proxy

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

Add end-to-end example of usage with SPFx #27

Closed koltyakov closed 6 years ago

koltyakov commented 6 years ago

1. Install SharePoint REST Proxy in SPFx solution project

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

2. Create proxy.js file in a root or wherever in the project with the following content:

const CertificateStore = require('@microsoft/gulp-core-build-serve/lib/CertificateStore');
const RestProxy = require('sp-rest-proxy');

const settings = {
  configPath: './config/private.json',
  port: 4323,
  protocol: 'https',
  ssl: {
    cert: CertificateStore.default.instance.certificateData,
    key: CertificateStore.default.instance.keyData
  }
};

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

3. Create npm task to execute, e.g. "proxy": "node ./proxy" 4. Run and configure proxy's connection to the environment by npm run proxy 5. Configure a task to start proxy and gulp serve at the same time, e.g. using concurrently or npm-run-all 6. In SPFx webpart use detection of a local mode with:

import { Environment, EnvironmentType } from '@microsoft/sp-core-library';
if (Environment.type === EnvironmentType.Local) {
  // Local mode
}

7. If local mode, target request to proxy's endpoint Example for sp-pnp-js:

if (Environment.type === EnvironmentType.Local) {
  this.web = new Web('https://localhost:4323/sites/site/web');
} else {
  setup({ spfxContext: this.context });
  this.web = new Web(this.context.pageContext.web.absoluteUrl);
}
koltyakov commented 6 years ago

Blog post article with setting up SPFx and Proxy