firebase Google Cloud Python Flask API的CORS问题

zpf6vheq  于 2023-06-30  发布在  Go
关注(0)|答案(1)|浏览(155)

我从另一个域调用托管在Google Cloud上的API时遇到CORS问题
这是我得到的错误:CORS策略已阻止从源“http://localhost:4200”(或“https://www.example.com”)访问“https://myapi.app/ask_question”处的XMLHttpRequestmywebsite.dev:对印前检查请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。
下面是调用我的API的代码(托管在https://mywebsite.dev上):

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

interface ChatMessage {
  text: string;
  isUserMessage: boolean;
}

@Component({
  selector: 'app-chatbot',
  templateUrl: './chatbot.component.html',
  styleUrls: ['./chatbot.component.css']
})
export class ChatbotComponent {
  isChatbotCollapsed = false;
  userInput: string = '';
  chatMessages: ChatMessage[] = [];

  constructor(private http: HttpClient) {}

  sendMessage() {
    const userMessage = this.userInput;

    this.chatMessages.push({ text: userMessage, isUserMessage: true });

    const apiUrl = 'https://myapi.app/ask_question';
    //const apiUrl = 'http://127.0.0.1:5000/ask_question';
    const payload = { input: userMessage };

    this.http.post(apiUrl, payload).subscribe(response => {
      const apiResponse = response as { output: string };
      const botResponse = apiResponse.output;

      this.chatMessages.push({ text: botResponse, isUserMessage: false });
    });

    this.userInput = '';
  }
}

下面是我的API代码(托管在https://myapi.app上):

import json
import os
from flask import Flask, request
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources={r"/*": {"origins":"https://mywebsite.dev"}})

@app.route('/ask_question', methods=['POST', 'OPTIONS'])
def ask_question():
    if request.method == 'OPTIONS':
        response = make_response()
        response.headers.add('Access-Control-Allow-Origin', 'https://mywebsite.dev')
        response.headers.add('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
        return response
    data = request.get_json()
    input_string = data['input']    
    output = 'hello, you said' + input_string
    
    response = make_response({'output': output})
    response.headers.add('Access-Control-Allow-Origin', 'https://mywebsite.dev')
    response.headers.add('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
    return response

if __name__ == '__main__':
    app.run()

有人知道我哪里做错了吗?
我尝试使用以下命令显式添加我的域:CORS(app, resources={r"*": {"origins": "*"}})CORS(app, resources={r"/*": {"origins": ["https://mywebsite.dev/", "https://mywebsite.firebaseapp.com/"]}})
我尝试在响应中添加标题:

@app.after_request
def add_cors_headers(response):
    response.headers['Access-Control-Allow-Origin'] = 'https://mywebsite.dev'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
    response.headers['Access-Control-Allow-Methods'] = 'POST'
    return response

我尝试在谷歌云中为CORS添加环境变量
这些都不管用

kmbjn2e3

kmbjn2e31#

这个错误似乎来自于我配置CORS响应头的方式,但这是因为我忘记在我的需求中添加flask_cors==4.0.0。我加的,还能用
在浏览器中,我们所能看到的是一个CORS错误,我试图通过添加具有确切起源的标题以及OPTION和POST方法来具体化,但我仍然有同样的错误,我试图通过将起源替换为“*”来更通用,但我仍然有同样的错误:
myapi.app/:1 从源“https://www.example.com”访问“https://myapi.app/ask_question”处的XMLHttpRequestmywebsite.dev已被CORS策略阻止:对印前检查请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。
通过检查云运行日志条目,我发现有两种类型的错误,一种是关于CORS的OPTION上的503,另一种是:
从flask_cors导入CORS。ModuleNotFoundError:没有名为'flask_cors'的模块“
感谢您发送编修。

相关问题