错误 - 跨源请求错误

时间:2017-07-27 15:45:52

标签: php laravel .htaccess ionic2 cross-domain

我正在使用laravel框架在php中开发一个api,它返回离子应用程序的记录。所以问题是我发送图像和文件路径,当尝试使用cross origin error下载文件时应用程序出错。

该方法发送一个像这样的json:

[{
"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"
}]

我有另一种获取文件的方法(路径):

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

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

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

如果确实在浏览器上使用它,它会将文件下载到我的笔记本电脑,但是当我尝试将文件发送到应用程序时它会给我cross origin error

搜索完此后,我更新了我的.htaccess添加以下行:

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

我该如何解决这个问题?

谢谢

1 个答案:

答案 0 :(得分:1)

通过open terminal或windows cmd命令在laravel中创建新的middleware

php artisan make:middleware CorsMiddleware

或者您想使用任何名称

并输入此代码

<?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);
    }
}

使用此Middleware在每次向您的应用程序发出请求时运行

Kernel.php目录中打开Http并注册Middleware

protected $middleware = [

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

]