[Python] Getting XMLHTTPrequest CORS error in python

Discussão em 'Python' iniciado por Stack, Abril 9, 2025.

  1. Stack

    Stack Membro Participativo

    I'm building a sample app in Flutter calling Python backend. Whenever flutter call the backend URL, I receive XMLHTTPRequest error. I'll be grateful if someone can help.

    My flutter code is as follow:

    Future<void> fetchSubjects() async {
    var url = Uri.parse('http://localhost:8000/subjects');
    try {
    final response = await http.get(
    url,
    headers: {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers":
    "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers",
    },
    );


    Python code is as follow:

    class S (BaseHTTPRequestHandler):
    def do_OPTIONS(self):
    print("OPTIONS request received")
    # Handle preflight requests
    self.send_response(200)
    self.send_header('Access-Control-Allow-Origin', '*')
    self.send_header('Access-Control-Allow-Methods', 'GET, POST')
    self.send_header('Access-Control-Allow-Headers', 'Content-Type')
    self.send_header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers")
    self.end_headers()

    def do_GET(self):
    self.send_header('Access-Control-Allow-Origin', '*')
    self.send_response(200)
    self.end_headers()
    self.wfile.write(b'Hello, World!')

    def run(server_class=HTTPServer, handler_class=S, port=8000):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    fetchSubjects()
    print(f'Starting server on port {port}...')
    httpd.serve_forever()
    if __name__ == '__main__':
    run()


    i tried adding CORS headers both in Flutter and in Python but still getting the error

    The following error is received when I run the above code. enter image description here

    Continue reading...

Compartilhe esta Página