Javascript CORS策略已阻止访问获取“url”:否';访问控制允许原点';请求的资源上存在标头。反应
我正试图用下面的代码在开发模式下从react应用程序获取一个无服务器函数Javascript CORS策略已阻止访问获取“url”:否';访问控制允许原点';请求的资源上存在标头。反应,javascript,python,reactjs,google-cloud-functions,fetch-api,Javascript,Python,Reactjs,Google Cloud Functions,Fetch Api,我正试图用下面的代码在开发模式下从react应用程序获取一个无服务器函数 let response = await fetch(url, { method: 'POST', mode: 'cors', body: "param=" + paramVar, }) .then(response => response.json()); 后端函数是一个Python
let response = await fetch(url,
{
method: 'POST',
mode: 'cors',
body: "param=" + paramVar,
})
.then(response => response.json());
后端函数是一个Python云函数,其代码如下:
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”出现在标题中,因此我真的不明白此错误的原因。将内容类型标题添加到前端的获取方法中,然后重试:
let response = await fetch(url,
{
method: 'POST',
mode: 'cors',
body: "param=" + paramVar,
headers: {
'Content-Type': 'application/json'
},
}).then(response => response.json());
将内容类型标头添加到前端的fetch方法中,然后重试:
let response = await fetch(url,
{
method: 'POST',
mode: 'cors',
body: "param=" + paramVar,
headers: {
'Content-Type': 'application/json'
},
}).then(response => response.json());
在后端安装CORS包。 然后打开server.js文件或任何属于您的文件。 然后将其导入文件
const cors = require('cors');
然后使用它
app.use(cors());
重新加载浏览器,应该完成 在后端安装CORS包。 然后打开server.js文件或任何属于您的文件。 然后将其导入文件
const cors = require('cors');
然后使用它
app.use(cors());
重新加载浏览器,应该完成 后端实际上有一个bug,它只是由浏览器添加的一些附加头触发的。在这种情况下,服务器返回404错误,该错误不包含我的头定义,并将导致CORS策略块
在我使用devtools跟踪浏览器发送的请求并复制curl请求中的所有头之后,我才能够识别这个bug。在修复了功能逻辑之后,问题得到了解决。实际上后端有一个bug,它只是由浏览器添加的一些附加头触发的。在这种情况下,服务器返回404错误,该错误不包含我的头定义,并将导致CORS策略块
在我使用devtools跟踪浏览器发送的请求并复制curl请求中的所有头之后,我才能够识别这个bug。在修复函数逻辑后,问题被修复。
应该允许选项方法
-代码不是这样做的吗@charlietfl<代码>如果request.method=='OPTIONS'此问题可能由于不同的原因而发生。看看这个,它可能会帮助您解决问题。应该允许选项方法
-代码不是这样做的吗@charlietfl<代码>如果request.method=='OPTIONS'此问题可能由于不同的原因而发生。看看这个,它可能会帮助您解决问题。