跨域图像上传Angular + laravel

时间:2016-01-03 19:04:11

标签: angularjs laravel-5 cors ng-file-upload

我一直在努力在服务器上上传图片。我在前端使用ngFileUpload。但我总是得到

“对预检请求的响应未通过访问控制检查:请求的资源上没有'Access-Control-Allow-Origin'标头”

文件上传的角色代码:

 var uploadFile = function (file) {
      if (file) {

            if (!file.$error) {
              Upload.upload({
                  url: baseUrl+'upload',
                  file: file


              }).progress(function (evt) {
                  var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                  //console.log(evt.total);
              }).success(function (data, status, headers, config) {
                  $timeout(function() {

                    console.log(data);
                    console.log(status);
                      if(status==200)
                        {

                          logo_path = data.logo_path;

                        }

                  });
              });
            }

      }
  };

在Laravel上我已经像这样配置了CORS:

public function handle($request, Closure $next)
{
    header("Access-Control-Allow-Origin: http://localhost:8001/");

    // ALLOW OPTIONS METHOD
    $headers = [
        'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
        'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
    ];
    if($request->getMethod() == "OPTIONS") {
        // The client-side application can set only headers allowed in Access-Control-Allow-Headers
        return Response::make('OK', 200, $headers);
    }

    $response = $next($request);
    foreach($headers as $key => $value)
        $response->header($key, $value);
    return $response;
}

普通跨域POST请求正常。即$ http.post()。我在角度上尝试了许多不同的标题变体但没有帮助。此外,OPTIONS请求返回200 OK,但仍显示预检响应失败消息。任何人都可以帮我解决这个问题的进一步调试吗?

1 个答案:

答案 0 :(得分:8)

尝试添加:

header('Access-Control-Allow-Origin: *'); 
header('Access-Control-Allow-Headers: Origin, Content-Type'); 
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');

在bootstrap / app.php中 您也可以在此处插入访问控制所需的任何其他标头。