V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
yazoox

为什么我没有办法 从 aws 的 s3 上面 fetch 文件?直接 forgidden 了......

  •  
  •   yazoox · Oct 19, 2021 · 2786 views
    This topic created in 1663 days ago, the information mentioned may be changed or developed.

    首先,我生成了一个 pre-signed url,然后其它人,upload 了一个 text 文件到这个 pre-signed url 。设名字为 result.txt

    接着,我的 web app,使用默认的 fetch method 直接去访问这个 pre-signed url,想下载这个 result.txt 。结果碰到了 CORS error 。我尝试着,直接用浏览器 chrome,打开这个 pre-signed url,能够正常下载这个 result.txt

    然后,我又添加了 fetch 参数 no-cors,但是报错 403, forbidden

          const res = fetch(pre-signed-url, {
            method: "GET",
            mode: "no-cors",
            headers: {
              Accept: "text/plain",
              "Content-Type": "text/plain"
            }
          });
    

    我又试了 axios, 但这个没有 mode 'no-cors'的设置,于是如下设置,得到的是 CORS error

      const res: AxiosResponse<any> = await axios.get(url, {
        method: "GET",
        withCredentials: false,
        headers: {
          "Access-Control-Allow-Origin": "*",
          Accept: "text/plain",
          "Content-Type": "text/plain"
        }
      });
      return res;
    

    这个,接下来,除了去设置 xxx.s3.amazonaws.com 的 allow list 之外,还有什么方法么?

    是不是我的 fetch 或者 axios.get 的参数设置不正确?为什么会被 forbidden?

    4 replies    2021-10-19 14:13:35 +08:00
    walkersz
        1
    walkersz  
       Oct 19, 2021
    AWS S3,设置一下 CORS 允许的域名( web app 的域名)
    EridanusSora
        2
    EridanusSora  
       Oct 19, 2021
    Access-Control-Allow-Origin 是服务端设置不是客户端设置!
    解决方案如 1 楼所说
    miniwade514
        3
    miniwade514  
       Oct 19, 2021
    mode: "no-cors" 并不是帮我们绕过 CORS,可以看一下这里的回答 https://stackoverflow.com/a/43268098/1564653
    跨域的关键还是服务端返回的 header 里要有 Access-Control-Allow-Origin
    yazoox
        4
    yazoox  
    OP
       Oct 19, 2021
    @miniwade514
    嗯,这个回复我也看到了。如果 server 的 response's header 里面,没有 Access-Control-Allow-Origin 的话,mode: 'no-cors'也没有用。但是如果有的话,就可以生效了。所以,还是得检查服务器端的设置。

    谢谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3034 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 130ms · UTC 13:26 · PVG 21:26 · LAX 06:26 · JFK 09:26
    ♥ Do have faith in what you're doing.