Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 227
mst Avatar asked Oct 24 '18 14:10

mst


People also ask

How do you resolve the CORS problem?

Cross-Origin Resource Sharing (CORS) errors occur when a server doesn't return the HTTP headers required by the CORS standard. To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard.

Why do CORS fail?

Or, your API fails and shows a CORS error in the console. This happens because the same-origin policy is part of the browser's security model which allows websites to request data from APIs of the same URL but blocks those of different URLs. Browsers do this by adding an ORIGIN key in the request.

What is content type multipart form data?

multipart/form-data [RFC1867] The multipart/form-data content type is intended to allow information providers to express file upload requests uniformly, and to provide a MIME-compatible representation for file upload responses.

Why postman is not affected by CORS?

The CORS standard is a client-side standard, implemented in the browser. So it is the browser which prevent the call from completing and generates the error message - not the server. Postman does not implement the CORS restrictions, which is why you don't see the same error when making the same call from Postman.


2 Answers

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);         
}
like image 94
mst Avatar answered Sep 30 '22 11:09

mst


I have the same problem ,Requests (GET/POST/PUT/DELTE) all work, only fileupload with Content-type:"multipart/form-data" got the CORS problem. I tried many times with headers "Access-Control-Allow-Origin ,Access-Control-Allow-Methods, Access-Control-Allow-Headers". Still not work

Finally, I found the nginx limited the File Upload Size. So, I add "client_max_body_size 10M" in nginx conf file.

The cors problem solved.

like image 35
tang wei Avatar answered Sep 30 '22 12:09

tang wei