gpt4 book ai didi

javascript - “Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response” 尽管 CORS 配置有效

转载 作者:行者123 更新时间:2023-12-04 00:55:57 29 4
gpt4 key购买 nike

我使用 Google Cloud Functions 创建了一个 API 端点,并试图从 JS 获取函数中调用它。
我遇到了我很确定与 CORS 或输出格式有关的错误,但我不确定发生了什么。其他一些 SO 问题类似,并帮助我意识到我需要删除 mode: "no-cors" .大多数人提到在 BE 上启用 CORS,所以我添加了 response.headers.set('Access-Control-Allow-Origin', '*') - 我在 this article 中了解到的- 确保启用 CORS...但我仍然收到“无法获取”错误。
完整错误(可在下面链接的现场演示中重现)是:

Uncaught Error: Cannot add node 1 because a node with that id isalready in the Store. (This one is probably unrelated?)

Access to fetch at'https://us-central1-stargazr-ncc-2893.cloudfunctions.net/nearest_csc?lat=37.75&lon=-122.5'from origin 'https://o2gxx.csb.app' has been blocked by CORS policy:Request header field access-control-allow-origin is not allowed byAccess-Control-Allow-Headers in preflight response.

GEThttps://us-central1-stargazr-ncc-2893.cloudfunctions.net/nearest_csc?lat=37.75&lon=-122.5 net::ERR_FAILED

Uncaught (in promise) TypeError: Failed to fetch


请参阅下面的代码片段,请注意我在哪里使用 <---- *** Message ***表示最近更改的代码部分,给了我这两个错误之一。
前端代码:
function getCSC() {
let lat = 37.75;
let lng = -122.5;

fetch(
`https://us-central1-stargazr-ncc-2893.cloudfunctions.net/nearest_csc?lat=${lat}&lon=${lng}`,
{
method: "GET",
// mode: "no-cors", <---- **Uncommenting this predictably gets rid of CORS error but returns a Opaque object which seems to have no data**
headers: {
// Accept: "application/json", <---- **Originally BE returned stringified json. Not sure if I should be returning it as something else or if this is still needed**
Origin: "https://lget3.csb.app",
"Access-Control-Allow-Origin": "*"
}
}
)
.then(response => {
console.log(response);
console.log(response.json());
});
}
后端代码:
import json
import math
import os
import flask

def nearest_csc(request):
"""
args: request object w/ args for lat/lon
returns: String, either with json representation of nearest site information or an error message
"""

lat = request.args.get('lat', type = float)
lon = request.args.get('lon', type = float)

# Get list of all csc site locations
with open(file_path, 'r') as f:
data = json.load(f)
nearby_csc = []

# Removed from snippet for clarity:
# populate nearby_csc (list) with sites (dictionaries) as elems
# Determine which site is the closest, assigned to var 'closest_site'

# Grab site url and return site data if within 100 km
if dist_km < 100:
closest_site['dist_km'] = dist_km

// return json.dumps(closest_site) <--- **Original return statement. Added 4 lines below in an attempt to get CORS set up, but did not seem to work**

response = flask.jsonify(closest_site)
response.headers.set('Access-Control-Allow-Origin', '*')
response.headers.set('Access-Control-Allow-Methods', 'GET, POST')
return response

return "No sites found within 100 km"
上面代码片段的更完整上下文:
  • 这是 Code Sandbox Demo上面提到的。
  • 这里是 full BE code on GitHub ,减去最近添加 CORS 的尝试。
  • API endpoint .

  • 我还想知道 CodeSandbox 是否有可能以一种奇怪的方式执行 CORS,但在 localhost:3000 上运行它时遇到了同样的问题。 ,当然在 prod 中也会有这个在我自己的个人领域。
    错误似乎与 CORS 相关( 'https://o2gxx.csb.app' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. )但我想添加 response.headers.set('Access-Control-Allow-Origin', '*')会解决的。我需要在 BE 上更改其他内容吗?在FE上?
    TLDR;
    即使在尝试在后端启用 CORS 并将 header 添加到 FE 之后,我也收到错误“无法获取”和“Access-Control-Allow-Headers 不允许字段访问控制允许来源”。有关代码的实时演示,请参见上面的链接。

    最佳答案

    删除前端代码中添加 Access-Control-Allow-Origin 的部分标题。
    从不添加 Access-Control-Allow-Origin作为前端代码中的请求 header 。
    唯一的影响是负面的:它会导致浏览器进行 CORS 预检 OPTIONS即使在来自前端代码的实际(GETPOST 等)请求不会触发预检的情况下,也会发出请求。然后预检将失败并显示以下消息:

    Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response


    …也就是说,除非请求的服务器已配置为发送 Access-Control-Allow-Headers: Access-Control-Allow-Origin,否则它将失败。响应头。
    但你永远不会想要 Access-Control-Allow-OriginAccess-Control-Allow-Headers响应头值。如果这最终使事情正常进行,那么您实际上只是在解决错误的问题。因为真正的解决方法是:从不设置 Access-Control-Allow-Origin作为请求头。
    直觉上,将其视为“我设置了 Access-Control-Allow-Origin 似乎合乎逻辑。无论是在请求中还是在响应中,所以这应该比仅仅在响应中更好”——但它实际上比只在响应中设置它更糟糕(出于上述原因)。
    所以底线: Access-Control-Allow-Origin只是一个响应头,而不是请求头。您只想在服务器端响应代码中设置它,而不是前端 JavaScript 代码。

    问题中的代码也试图添加 Origin标题。您也永远不想尝试在前端 JavaScript 代码中设置该 header 。
    Access-Control-Allow-Origin 的情况不同 header , Origin实际上是一个请求头——但它是一个完全由浏览器控制的特殊头,浏览器永远不会允许你的前端 JavaScript 代码设置它。所以永远不要尝试。

    关于javascript - “Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response” 尽管 CORS 配置有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62569594/

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