0
votes

I have a laravel application which I've created various api's and they sit awaiting my applications to post / get.

I am developing a ionic app which utilizes Ngresource and sends the post request, however on testing I get the following error:

XMLHttpRequest cannot load http://IPADDRESS/api/test Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

I have tried on my laravel application wrapping my api routes in a middleware group which includes the middleware CORS. I have also registered the middleware in my Kernel.php file. see below cors middleware.

<?php namespace App\Http\Middleware;
use Closure;

use Illuminate\Contracts\Routing\Middleware;
use Illuminate\Http\Response;

class CORS implements Middleware {

 /**
  * 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-Origin' , '*')
          ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
          ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With');
 }
}

but this has made no difference and I get the same error.

2
try modifying your hosts file for www.mylarveltest.com against your loopback ip 127.0.0.1 and try using mylarveltest.com/api/test - Abhishek Singh
what part of this has to do with SSH ? - lagbox
Sorry @AbhishekSingh my laravel site is hosted already my ionic app is locally hosted - Dev.W
@Wolrab locally hosted iconic app cannot send requests to web hosted apps due to cross origin effect. Please build the app and deploy on phone. It should work - Abhishek Singh
@AbhishekSingh would it still not work even if I use ionic view?? - Dev.W

2 Answers

1
votes

Quick dirty solution is install cors plugin in your browser and it will works.

CORS plugin for chrome .

-1
votes

If I understood it right you are doing an XMLHttpRequestto a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.

enter image description here