1

I'm developing an api in php with laravel framework that returns records for an ionic app. So the problem is that i send images and files paths and the app give an error when try to download the file with cross origin error.

The method sends a json like this:

[{
"name": "Braga",
"ref": "6903",
"cover": "/images/uploads/0_C6903_597614930f57e.jpg",
"coverDetail": "/images/uploads/0_D6903_597614930f599.jpg",
"pdf": "/images/uploads/0_P6903_597614930f5b0.epub",
"companyId": "0"
}]

And I have another method(path) to get file:

public function getFile($url){
$file= public_path(). $url;

$headers = array(
  'Content-Type: application/epub',
);

return Response::download($file, '', $headers);}

If did use that on browser it works, it downloads the file to my laptop but when I try to get the file to the app it gives me cross origin error.

After searching about this I update my .htaccess adding this lines:

<IfModule mod_headers.c>
        Header always set Access-Control-Allow-Origin "*"
        Header always set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Access-Control-Allow-Origin"
        Header always set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
</IfModule>

How can I solve this problem?

Thank you

user3242861
  • 1,839
  • 12
  • 48
  • 93

1 Answers1

1

Create new middleware in laravel by open terminal or windows cmd commands

php artisan make:middleware CorsMiddleware

Or any name would you like to use

And put this code

<?php

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)
    {

      $domains = ["http://example.com"];

        if(isset($request->server()['HTTP_ORIGIN'])){
          $origin = $request->server()['HTTP_ORIGIN'];

          if(in_array($origin,$domains)){
            header("Access-Control-Allow-Origin: " . $origin);
            header("Access-Control-Allow-Headers: Origin,Content-type,Authorization");
          }

        }

        return $next($request);
    }
}

And using this Middleware to run during every request to your application

Open Kernel.php in Http directory And register your Middleware

protected $middleware = [

    \App\Http\Middleware\CorsMiddleware::class,

]
Ali Turki
  • 1,265
  • 2
  • 16
  • 21