问题描述
我正在尝试使用以下代码从开发模式下的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': '*',}
# 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());
重新加载浏览器,应该完成!
,实际上后端中存在一个错误,该错误仅由浏览器添加的一些其他标头触发。在那种特定情况下,服务器返回404错误,该错误不包含我的标头定义,并且会导致CORS策略块。
在使用devtools跟踪浏览器发送的请求并复制curl请求中的所有标头之后,我才能够确定该错误。修复功能逻辑后,问题已解决。
,将内容类型标头添加到前端的fetch方法中,然后重试:
let response = await fetch(url,{
method: 'POST',mode: 'cors',body: "param=" + paramVar,headers: {
'Content-Type': 'application/json'
},}).then(response => response.json());