如果“内容类型”:“多部分/表单数据”

时间:2018-10-24 14:19:35

标签: file-upload cors multipartform-data nginx-config

我有两个域(客户端为example.com,其余API为api.example.com),我在其中考虑了CORS策略从客户端向API请求。 预检请求按预期方式工作,其他所有请求(GET / POST / PUT / DELTE)均正常运行(文件上传除外),这意味着Content-type是否为“ multipart / form-data”。

我在Chrome控制台中收到以下错误:

  

CORS策略已阻止从来源“ https://api.example.com/video/upload”访问“ https://www.example.com”处的XMLHttpRequest:请求的资源上没有“ Access-Control-Allow-Origin”标头。

这里是我的客户(vuejs)来源:

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

以及CORS的nginx配置:

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

有人可以让我知道此代码和配置有什么问题吗?! 感谢任何帮助!

2 个答案:

答案 0 :(得分:4)

我有同样的问题,请求(GET / POST / PUT / DELTE)都可以工作,只有Content-type:“ multipart / form-data”的文件上传出现了CORS问题。 我尝试使用标头“ Access-Control-Allow-Origin,Access-Control-Allow-Methods,Access-Control-Allow-Headers”多次。还是不行

最后,我发现nginx限制了文件上传大小。 因此,我在nginx conf文件中添加了“ client_max_body_size 10M”。

cors问题解决了。

答案 1 :(得分:1)

通过在应用程序端应用CORS来解决。

详细地,当浏览器发送预检请求时出现错误。因此,对于预检请求,我在应用程序端手动添加了Header。 我一直在使用Laravel做后端,因此创建了Cors中间件,就像下面这样:

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