mab3103 mab3103 - 3 months ago 30
Javascript Question

Ionic app CORS No 'Access-Control-Allow-Origin' header is present, using Lumen API with CORS middleware

I am building an app which uses a Lumen API. On the Lumen project I have two files which I found on the internet whilst looking up how to handle CORS in Lumen.


namespace App\Http\Middleware;
class CorsMiddleware {
public function handle($request, \Closure $next)
$response = $next($request);
$response->header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, PATCH, DELETE');
$response->header('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers'));
$response->header('Access-Control-Allow-Origin', '*');
return $response;


namespace App\Providers;
use Illuminate\Support\ServiceProvider;
* If the incoming request is an OPTIONS request
* we will register a handler for the requested route

class CatchAllOptionsRequestsProvider extends ServiceProvider {
public function register()
$request = app('request');
if ($request->isMethod('OPTIONS'))
app()->options($request->path(), function() { return response('', 200); });

These two files fixed my initial CORS issue. I am able to perform a GET and receive data from the API. But when I try a POST method to the API I once again get the following error: "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access."

Upon inspecting the network tab in chrome, There are two requests. The first is an OPTIONS request, which I believe is just to get the allowed headers from the server. The second request is my POST request with the correct payload. They both return a status code of 200 OK but I still get the Access-Control error mentioned above.

It works when using POSTMAN to send data to my API, but not when I use Ionic Serve in the browser

For those who are wondering, I am using Ionic's $http method for the call:

MORE CODE.......
var req = {
method: 'POST',
url: APIUrl + 'register',
timeout: timeout.promise,
data: {"name": "Michael"}

$http(req).then(function(res) {
.......MORE CODE

Might it be something to do with the server apache config? I have mod_rewrite enabled.
Any help on this would be greatly appreciated. Thanks


If you are in control of the server, you might need to set the required headers there. Depending on which server, this might help: