CORS Access-Control-Allow-Methods preflight denied


#1

Having issues communicating with an external API via ionic serve and ionic run -l, essentially anything that uses a localserver.

I’ve followed the guide @ http://blog.ionic.io/handling-cors-issues-in-ionic/, which provides an option for handling the issue in Ionic 1 projects, but I’m struggling to get it working in a v2 project.

Fetch API cannot load https://test.api.promisepay.com/items/100fd4a0-0538-11e6-b512-3e1d05defe79/make_payment. Method PATCH is not allowed by Access-Control-Allow-Methods in preflight response.

I have no control over how the API handles theses requests, as it is controlled by PromisePay.

Following the closest thing to a possible solution on StackOverflow: http://stackoverflow.com/questions/40576037/cors-with-firebaseionic2angularjs-no-access-control-allow-origin-still-exis

I’ve updated my ionic.config.json to

{
  "name": "project",
  "app_id": "xxxxxxx",
  "proxies": [{
    "path": "/ppapi",
    "proxyUrl": "https://test.api.promisepay.com"
  }]
}

In the library that makes the http calls, I’ve updated the base URL to const PRE_LIVE_API = '/ppapi';

The request method looks as follows:

let Requester = class Requester {
  constructor() {
    let config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

    this.config = config;
    const baseUrl = PRE_LIVE_API;
    this.log(`API endpoint: ${ baseUrl }`);
    this.client = _requestPromise2.default.defaults({
      baseUrl: baseUrl,
      auth: {
        user: config.userName,
        pass: config.token
      },
      headers: {
        Accept: 'application/json',
        Authorization: `basic ${ config.apiToken }`
      },
      resolveWithFullResponse: true
    });
  }

When making a call to the most basic of API endpoints /status/ I am now receiving the following error:

"Error: Invalid URI "/ppapi/status""

It seems the proxy path isn’t being passed through.

Any ideas?


#2

Solved. Explicitly setting the BaseURL constant (PRE_LIVE_BASE) to http://localhost:8100/ppapi resolves the issue. Now all requests are passed via the proxy alias and subvert the CORS issue.

The only downside of this approach, is that I had to change a variable that was part of a package in node_modules, which will be overwritten during any future updates. So I should probably create my own fork for a cleaner solution.