设置标头后,请求仍被CORS策略阻止

时间:2019-03-25 09:24:02

标签: python google-cloud-platform cors google-cloud-functions

我编写了一个云函数,该函数接受请求并对该请求执行处理。当它来自相同的API域时,它将按预期工作。但是在交叉API请求的情况下,出现以下错误:

Access to XMLHttpRequest at ’URL' from origin ‘URL2’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

即使我已经更改了Google云平台建议的代码,但仍无法正常工作

if request.method == 'OPTIONS':
    headers = {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'POST',
        'Access-Control-Allow-Headers': 'Authorization',
        'Access-Control-Max-Age': '3600',
        'Access-Control-Allow-Credentials': 'true'
    }
    return ("",200,headers)
headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'POST',
    'Access-Control-Allow-Headers': 'Authorization',
    'Access-Control-Max-Age': '3600',
    'Access-Control-Allow-Credentials': 'true'
}
return ("Successfully inserted",200,headers)

在python中发送OPTIONS请求时,标头为

{'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Headers': 'Authorization', 'Access-Control-Allow-Methods': 'POST', 'Access-Control-Allow-Origin': '*', 'Access-Control-Max-Age': '3600', 'Content-Type': 'text/html; charset=utf-8', 'Function-Execution-Id': '6bkxaumbvg7x', 'X-Cloud-Trace-Context': '2fd8aec285f8af1d36c8c45ff1184a20;o=1', 'Date': 'Mon, 25 Mar 2019 09:41:08 GMT', 'Server': 'Google Frontend', 'Content-Length': '0', 'Alt-Svc': 'quic=":443"; ma=2592000; v="46,44,43,39"'}

请咨询

1 个答案:

答案 0 :(得分:-1)

我刚刚注释掉了以下AJAX命令,该命令用于向python代码发送请求

//xhr.withCredentials = true;
//xhr.setRequestHeader("Postman-Token", "cecaf566-fd7a-4992-8b65-cc66c074f264");

成功了。 很抱歉没有首先发布AJAX,因为我认为问题出在服务器端,无法响应请求。