简体   繁体   中英

Ionic v2 + CORS Preflight Access-Control-Allow-Methods

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: CORS with Firebase+IONIC2+Angularjs: No 'Access-Control-Allow-Origin' still exists

I've updated my ionic.config.json to

{
  "name": "project",
  "app_id": "xxxxxxx",
  "proxies": [{
    "path": "/api",
    "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 = '/api';

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 "/api/status""

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

I was facing the same problem when I was trying to use the MailGun to send e-mails using REST API.

The solution is to use HTTP instead of http. ionic 2 provides the class [HTTP]: http://ionicframework.com/docs/v2/native/http/ .

In your projects root folder, run this command from the terminal:

ionic plugin add cordova-plugin-http

In your .ts file:

import { HTTP } from 'ionic-native';

Then, wherever you want to send the HTTP post/get using Basic Authentication, use this:

HTTP.useBasicAuth(username, password)
//replace username and password with your basic auth credentials

Finally, send the HTTP post using this method:

HTTP.post(url, parameters, headers)

Hope this helps! Good luck!

Solved. Explicitly setting the BaseURL constant (PRE_LIVE_BASE) to http://localhost:8100/api 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.

For Development purposes where the calling url is http://localhost , the browsers disallow cross-origin requests, but when you build the app and run it in mobile, it will start working.

For the sake of development, 1. Install CORS plugin/Extension in chrome browser which will help get over the CORS issue. 2. If the provider is giving a JSONP interface instead of a normal get/post, You will be able to get over the CORS issue.

I prefer using the 1st option as not a lot of api's provide a jsonP interface.

For Deployment, You need not worry as building a app & running it in your mobile, you will not face the same issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM