Cross Domain Image upload Angular+laravel

梦想的初衷 提交于 2020-01-03 07:19:06

问题


I have been struggling with image upload on server. I am using ngFileUpload on front end. But I always get

"Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource"

Angular Code for file Upload :

 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;

                        }

                  });
              });
            }

      }
  };

On Laravel i have configured CORS like this :

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

The Normal cross domain POST request works fine. i.e $http.post(). I have tried many different variations of headers on angular but none helps. Also the OPTIONS request returns 200 OK but still preflight response failure message is displayed. Can anyone help me with how to further debug this issue?


回答1:


Try adding:

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

in bootstrap/app.php You may also insert any other header you may need for access control here.



来源:https://stackoverflow.com/questions/34580415/cross-domain-image-upload-angularlaravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!