Search code examples
file-uploadcorsmultipartform-datanginx-config

CORS problem if "Content-type": "multipart/form-data"


I have two domains (example.com for client, api.example.com for rest API) where I request from client to API considering CORS policy. Preflight request works as expected and every other requests (GET/POST/PUT/DELTE) work well except file upload, means if Content-type is "multipart/form-data".

And I get following error in Chrome console:

Access to XMLHttpRequest at 'https://api.example.com/video/upload' from origin 'https://www.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here my client (vuejs) source:

var config = {
    headers: { "Content-Type": "multipart/form-data" },
    onUploadProgress(e) {
      if (e.lengthComputable) {
        self.percentage = Math.round(e.loaded / e.total * 100) + "%";
      }
    }
  };

  axios
    .post(apiUrl + `/video/upload`, formData, config)
    .then(response => {
      this.successes.push(
        response.data.videoName + " uploaded."
      );
    })
    .catch(e => {
      this.errors.push(message);
    });
},

And nginx configuration for CORS:

server {
listen 443 ssl default_server http2;
listen [::]:443 ssl default_server ipv6only=on;
root /var/www/example/public;
index       index.php index.html index.htm;
server_name api.example.com:443;

add_header Access-Control-Allow-Origin "*" always;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Access-Control-Allow-Methods "GET, POST, PUT, OPTIONS,  DELETE";
add_header Access-Control-Allow-Headers "Content-Type, X-Auth-Token, Origin, Authorization";

Could anyone please let me know what is wrong with this code & configuration?! Appreciate any help!


Solution

  • Solved it by applying CORS in application side.

    In detail, when browser sends preflight request error comes out. So, for the preflight requests I manually added Headers in application side. I have been using Laravel for backend, so created Cors middleware as floowing:

    public function handle($request, Closure $next) {
        if ($request->getMethod() == "OPTIONS") {   
            $headers = [    
                'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',    
                'Access-Control-Allow-Headers' => 'Content-Type, Origin, Authorization' 
            ];
            return \Response::make('OK', 200, $headers);    
        }   
    
        return $next($request);         
    }