Skip to content
Go back

R2 使用 presign url 前端老是报错

Edit page
Image

直接就去 R2 bucket 设置里面设置 CORS Policy1

[
  {
    "AllowedOrigins": ["http://localhost"],
    "AllowedMethods": ["GET", "PUT"],
    "AllowedHeaders": ["Content-type"]
  }
]

还是报错, 然后去查看 Access-Control-Allow-Headers2 查了 CORS-safelisted response header https://fetch.spec.whatwg.org/#cors-safelisted-request-header

看代码

return axios.put(presignedInfo.uploadUrl, options.file, {
  headers: {
    "Content-Type": options.file.type,
  },
});

设置也没问题啊, 但就是报错 (注意这里 PUT 不能直接 GET 查看, 这时候 403 和上述 OPTIONS 错误不是一个问题, 上述问题只是一个 CORS 报错, 这就是整个事件最大的乌龙了), 最后在 axios 社区3 提醒下, 设置允许 header 为 *

然后发现忘了 axios 中间件层设置了 tenant-id header 😅


教训:

The 403 response status indicates a general problem with the server backend not being configured to handle OPTIONS requests, not just CORS preflight OPTIONS requests.

The server must respond to OPTIONS requests with a 2xx success status—typically 200 or 204.

https://stackoverflow.com/questions/44966434/response-for-preflight-403-forbidden/44968217

Footnotes

  1. https://developers.cloudflare.com/r2/buckets/cors/

  2. https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Headers

  3. https://github.com/axios/axios/discussions/4478


Edit page
Share this post on:

Previous Post
一句
Next Post
android 使用通知滤盒, gotify 和 raycast 接收验证码