javascript - 尽管控制台中出现错误,仍发出 CORS 请求

标签 javascript cors google-cloud-storage fetch-api

我正在摆弄 Google Cloud Storage。我创建了一个简单的 Python Flask 处理程序:

#!/usr/bin/env python3
import secrets

import flask
from flask_cors import CORS
from google.cloud import storage


app = flask.Flask(__name__)
CORS(app)
client = storage.Client()
bucket = client.get_bucket('<my-bucket>')


@app.route('/')
def get_upload_urls():
    blob = bucket.blob('00000' + secrets.token_hex())
    return flask.jsonify({
        'url': blob.create_resumable_upload_session(),
    })


if __name__ == '__main__':
    app.run('0.0.0.0', 9999)

这伴随着一个非常简单的网络前端:

index.html:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="user-scalable=no,initial-scale=1,maximum-scale=1,minimum-scale=1,width=device-width">
    <title>Test</title>
  </head>
  <body>
      <input id="input" type="file" />
      <button id="button">Upload</button>
      <script src="index.js"></script>
  </body>
</html>

index.js:

const input = document.getElementById('input')
const button = document.getElementById('button')


button.addEventListener('click', async () => {
    const [ body ] = input.files
    const response = await fetch('http://localhost:9999')
    const { url } = await response.json()
    await fetch(url, {
        method: 'PUT',
        body,
    })
})

这个前端允许我选择一个文件,并使用 Python 后端创建的可恢复上传 session 将其上传到 Google Cloud Storage。

问题是它确实有效。我预计 PUT 请求会失败,但事实并非如此。

选择文件并按下上传按钮后,控制台将记录以下错误:

index.html:1 Failed to load https://www.googleapis.com/upload/storage/v1/b//o?uploadType=resumable&upload_id=: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3333' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

index.js:13 Uncaught (in promise) TypeError: Failed to fetch
  async function (async)
  button.addEventListener @ index.js:5

但是,PUT 请求已成功发出,并且文件显示在 Google 云存储中。我可以下载它,看起来完全没问题。

尽管控制台中出现 CORS 错误,但为什么 PUT 请求没有失败?

编辑:

我只是在寻找解释,而不是寻找解决方法 - 无论如何我都会正确配置 CORS。我只是想知道为什么请求没有失败,以及为什么 fetch 会拒绝。

最佳答案

@sideshowbarker 是对的,我也遇到了同样的问题。除了 OPTIONS 预检请求之外,还需要在 PUT 响应中设置 CORS。然后 fetch 将成功(即使之前上传成功)。

关于javascript - 尽管控制台中出现错误,仍发出 CORS 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46971451/

相关文章:

javascript - 如何在 "AND"关系中组合 deferreds/promise,但不将单个拒绝计为整体拒绝?

javascript - 如何将 SVG 嵌入到来自 Cross Origin url 的 html <object> 标签中(s3_url/image.svg)

reactjs - 类型错误 : "NetworkError when attempting to fetch resource."

javascript - Google Storage 签名 URL 过期导致 400 错误,没有 CORS header

google-cloud-platform - 云函数可以从云存储中读取吗?

javascript - 如何在 jQuery 中控制我的悬停事件?

javascript - dojo.addOnLoad() 永远不会在 GWT 页面中触发

http - 更改 http header 后浏览器发送 Options 而不是 Post

python - Beam/Dataflow 自定义 Python 作业 - Cloud Storage 到 PubSub

javascript - 如何显示这样的嵌套列表?