Problem with CORS using Ionic and Lumen

Asked

Viewed 781 times

1

I’m developing an app with Ionic and using Lumen in the backend API. I am having problems with 'CORS', already configured the server (both using the internal PHP server and Apache, and the same error occurs in both) creating a middleware for CORS that adds the options to the header as it didn’t work disabled this middleware and installed the middleware available in this barryvdh/Laravel-Cors set it up to run with an error by calling the API via the Ionic app. If I do a test using Postman the test is performed normally and it is possible to notice that the header headers appear as they should. I did several searches and all refer the CORS configuration in the headers of the answers that the server sends. I really have no idea where the problem might be. Below follow the codes and picture of the errors. Imagem do erro após chamada no ionic

The middleware code I created myself:


namespace App\Http\Middleware;

use Closure;

class CorsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Headers', "Origin, X-Requested-With, Content-Type, Accept")
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Credentials', true);
    }
}

As the above code did not work I disabled that middleware and installed the middleware of the barryvdh/Laravel-Cors project. In the app.php file I added the lines:


$app->routeMiddleware([
     'cors' => \Barryvdh\Cors\HandleCors::class
 ]);
$app->configure('cors');
$app->register(\Barryvdh\Cors\ServiceProvider::class);

The Response header with the middleware that I created by requesting by Postman is the one in the figure below:

inserir a descrição da imagem aqui

And using the middleware of the barryvdh/Laravel-Cors design is the figure below:

inserir a descrição da imagem aqui

To finish I’ll put the call to the API as it is in the Ionic app (the Ionic app is writing under http://localhost:8100):


avancar(){
    this.http.post('http://localhost/api/public/clientes/novo', this.data)
      .map(res => res.json())
      .subscribe(
        res => console.log(res),
        error => console.log(error)
      );
    this.navCtrl.setRoot(ConfirmacaoPage);
  }

Thank you all!

  • After a few tests I realized that running the app directly on mobile works but not in the browser. I will keep the question because someone may know why it does not work in the browsers. Note: middleware is configured in the routes.

3 answers

0


Use Chrome Canary and disable the CORS check flag when opening the app.

I am in a UNIX environment, I use the following alias inside my bash_profile to open:

alias canary="open -a /Applications/Google\ Chrome\ Canary.app --args --disable-web-security --user-data-dir=$HOME/canary"

I noticed that you are on Windows, so I believe that the flags needed to disable are passed in the properties of the shortcut that links to the Chrome Canary executable.

I couldn’t make it work that way with normal Chrome, but used a extension that worked, changed only for ease same.

  • I’m not in windows, I’m in linux. But I used the extension and it worked. But it is funny pq even adding the headers that allow the CORS it does not work in the browser but works in the APP. Anyway using the extension solves the problem to test the code made with Ionic.

0

WHAT IS CORS?

  • CORS defines a means by which a browser and a web server can interact to determine whether or not to use/allow cross-source requests.

When a CORS validation is performed?

  • When the source is different and/or when the request header is added new parameter (Ex: tokenAPI, userAPI).

From this, we understand that you are calling from an X server to an API on a Y server or adding some custom parameter to header.

Right now, the framework is calling OPTIONS passing to ORIGEM and the additional parameters in HEADER (If any) for the endpoint of the request.

It is in this request OPTION that the framework validates whether or not the server accepts the request.

By the first print shown, your API does not respond to method OPTION. You need to implement this method with the Sponse validations:

Access-Control-Allow-Methods : OPTIONS, GET, POST, PUT, DELETE
Access-Control-Allow-Headers : origin, content-type, accept, userAPI(Parâmetro customizado), tokenAPI(Parâmetro customizado)
Access-Control-Allow-Origin  : *

-1

Whoa, let’s split up: - The middleware of the barryvdh/Laravel-Cors project, when added in a non-global way, has to be added on routes, via route group or individually;

  • In Ionic, you did not specify the version, I remember that there is a white list, in which you have to put the domain in which it can make http calls.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.