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

mst picture mst · Oct 24, 2018 · Viewed 8.1k times · Source

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!

Answer

tang wei picture tang wei · Jun 12, 2020

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.