gpt4 book ai didi

javascript - 获取 `url` 的访问被 CORS 策略 : No 'Access-Control-Allow-Origin' header is present on the requested resource. ReactJS 阻止

转载 作者:行者123 更新时间:2023-12-05 00:27:02 32 4
gpt4 key购买 nike

我正在尝试使用以下代码从开发模式下的 react 应用程序中获取无服务器功能。

let response = await fetch(url,
{
method: 'POST',
mode: 'cors',
body: "param=" + paramVar,
})
.then(response => response.json());
后端函数是一个 Python Cloud 函数,代码如下:
def main(request):
# CORS handling
if request.method == 'OPTIONS':
# Allows GET requests from any origin with the Content-Type
# header and caches preflight response for an 3600s
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '3600'
}

return ('', 204, headers)

# Set CORS headers for the main request
headers = {
'Content-Type':'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
}

# Process request
return (json.dumps(response), 200, headers)
但我不断收到以下错误:
Access to fetch at 'url' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
当我尝试使用 curl 执行相同的请求时,我得到了正确的响应。使用 curl 获取选项给了我以下信息:
HTTP/2 204
access-control-allow-headers: Content-Type
access-control-allow-methods: GET, POST
access-control-allow-origin: *
access-control-max-age: 3600
content-type: text/html; charset=utf-8
date: Sun, 16 Aug 2020 01:29:41 GMT
任何人都可以帮助我理解为什么我无法在前端得到响应?标题中存在“Access-Control-Allow-Origin”,所以我真的不明白这个错误的原因是什么。

最佳答案

在后端安装 CORS 包。
然后打开您的 server.js 文件或您的任何文件。
然后将其导入文件

const cors = require('cors');
然后使用它
app.use(cors());
重新加载浏览器,应该完成!

关于javascript - 获取 `url` 的访问被 CORS 策略 : No 'Access-Control-Allow-Origin' header is present on the requested resource. ReactJS 阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63432473/

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