gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:02:32 26 4
gpt4 key购买 nike

我正在摆弄 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com