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.
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:
And using the middleware of the barryvdh/Laravel-Cors design is the figure below:
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.
– Marcos da Cruz Sibilio Jr.