API 即使启用了 CORS,Gate away 也会被阻止

API Gate away Is Blocked even when CORS is enabled

我正在尝试制作一个 api 来像这样将图像上传到 cloudinary

    fd.append('photos', file);
    fd.append('upload_preset', 
         CLOUDINARY_UPLOAD_PRESET);

    axios({
        url: CLOUDINARY_API,
        method: 'POST',
        headers: {

            'Content-Type': 'application/x-www-form-urlencoded',
            "Access-Control-Allow-Origin": "*",
            'Access-Control-Allow-Headers': 'Origin',
            'Access-Control-Allow-Credentials': true
        },
        data: fd
    }).then(function(res) {
        console.log(res);
    }).catch(function(err) {
        console.error(err);
    })

})

但我从浏览器收到此错误

Access to XMLHttpRequest at 'https://api.cloudinary.com/v1_1/******/mh/upload' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.Blockquote

您需要从您发送的请求中删除三个“Access-Control-Allow-*”headers。

headers Cloudinary 允许 cross-origin 请求不包括您发送的那些 headers,因此浏览器会抛出此错误。

以下是允许 cross-origin 上传的 headers(在 Access-Control-Allow-Headers 下):

curl -sD - -X OPTIONS https://api.cloudinary.com/v1_1/demo/image/upload

HTTP/1.1 200 OK
Access-Control-Allow-Headers: Cache-Control, Content-Disposition, Content-MD5, Content-Range, Content-Type, DPR, Viewport-Width, X-CSRF-Token, X-Prototype-Version, X-Requested-With, X-Unique-Upload-Id
Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS
Access-Control-Max-Age: 1728000
Cache-Control: no-cache
Content-Type: text/plain; charset=utf-8
Date: Sat, 19 Dec 2020 09:49:48 GMT
Server: cloudinary
Status: 200 OK
Vary: Accept-Encoding
X-Request-Id: d1af2a2f8a986d9ebbd1f14399dd409d
X-UA-Compatible: IE=Edge,chrome=1
X-XSS-Protection: 1; mode=block
Content-Length: 0
Connection: keep-alive

编辑:此外,Cloudinary API 没有名为“照片”的参数。要上传的文件在“文件”参数中发送。 因此,您需要将 fd.append('photos', file); 替换为 fd.append('file', file);.