- 
                Notifications
    You must be signed in to change notification settings 
- Fork 1.4k
Add a Proxy to browsersync
If you have an API Server running on a different port, you may want to proxy requests from you application to your api.
You can do this by adding a middleware to browsersync. (Shortcut)
One way to do this is by installing the proxy-middleware.
npm install proxy-middleware --save-devThen open the file tools/config/project.config.ts.
At the top of the file you include the proxy-middleware by
const proxy = require('proxy-middleware');As the default browsersync config is defined in tools/config/seed.config.ts we would overwrite it in our project specific settings (tools/config/project.config.ts):
So, you could simply copy the default config:
this.BROWSER_SYNC_CONFIG: any = {
  middleware: [require('connect-history-api-fallback')({index: `${this.APP_BASE}index.html`})],
  port: this.PORT,
  startPath: this.APP_BASE,
  server: {
    baseDir: `${this.DIST_DIR}/empty/`,
    routes: {
      [`${this.APP_BASE}${this.APP_DEST}`]: this.APP_DEST,
      [`${this.APP_BASE}node_modules`]: 'node_modules',
      [`${this.APP_BASE.replace(/\/$/,'')}`]: this.APP_DEST
    }
  }
};and place it in the project config. But first, we need to change a few things here:
- Move the top-level middleware property inside the server property.
- Then, add the proxy as first middleware before the connect-history-api-fallback.
Place the following snippet right after the super() call in the constructor():
this.BROWSER_SYNC_CONFIG: any = {
  port: this.PORT,
  startPath: this.APP_BASE,
  server: {
    baseDir: `${this.DIST_DIR}/empty/`,
    middleware: [
      proxy({
        protocol: 'http:',
        hostname: 'localhost',
        port: 8080,
        pathname: '/api',
        route: '/api'
      }),
      require('connect-history-api-fallback')({index: `${this.APP_BASE}index.html`})
    ],
    routes: {
      [`${this.APP_BASE}${this.APP_DEST}`]: this.APP_DEST,
      [`${this.APP_BASE}node_modules`]: 'node_modules',
      [`${this.APP_BASE.replace(/\/$/,'')}`]: this.APP_DEST
    }
  }
};This configuration will proxy all requests starting with /api (route-property) to another server on localhost:8080/api.
This is the shortcut version to add a proxy to localhost:8080 for any requests on /api
npm install proxy-middleware --save-devreplace tools/config/project.config.ts with the gist here