Getting CORS error after repeated allowing * origins

I’m using Flask and accessing a path from a frontend. Here’s my current Python:

from flask import Flask, jsonify, request
from flask_cors import CORS
from github import Github

app = Flask(__name__)
CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

@app.route('/call', methods=['POST', 'OPTIONS'])
def call():
    if request.method == 'OPTIONS':
        # Pre-flight request. Reply successfully:
        resp = app.make_default_options_response()
        headers = None
        if 'ACCESS_CONTROL_REQUEST_HEADERS' in request.headers:
            headers = request.headers['ACCESS_CONTROL_REQUEST_HEADERS']

        h = resp.headers
        h['Access-Control-Allow-Origin'] = '*'
        h['Access-Control-Allow-Methods'] = 'POST, OPTIONS'  # Add this line
        if headers is not None:
            h['Access-Control-Allow-Headers'] = headers

        return resp
    try:
        data = request.json
        if data is None:
            return jsonify(success=False, error='No JSON data provided'), 400

        github = Github(os.environ['GITHUB_TOKEN'])
        repo = github.get_repo('blank/blank.github.io')

        for file_name, file_content in data['files'].items():
            repo.create_file(f"{data['name']}/{file_name}", 'Deploy', file_content)

        url = f"https://blank.github.io/{data['name']}"

        return jsonify(success=True, url=url), 200
    except Exception as exception:
        return jsonify(success=False, error=str(exception))

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

That’s after repeated and failed attempts to fix it, so it’s possible that most of that bloat doesn’t actually do anything.

Here’s my JS (frontend):

const response = fetch("https://myurl.com/call", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    name: document.querySelector("#example input").value,
    files: files.reduce((obj, item) => {
      let escapedValue = item.value.replaceAll(/"/g, '\\"');
      obj[item.fileName] = escapedValue;
      return obj;
    }, {}),
  }),
}).then(() => {
  document.querySelector("#example > h4").style.color = "limegreen";
  for (let i = 0; i < 10; i++) {
    shootConfetti();
  }
});

(I renamed some of the element things just now to hide my project’s context (some may know it), but those elements do indeed exist so it’s not a problem with that)

Please help because I am like, way too confused. Oh, might I mention that I am hosting it with Cyclic.sh so it could be a problem with that (It used to work when I prototyped on Replit. I also have deployment logs there). Thank you!

Does anyone know the problem?

This kinda of error was quite common when you are developing web applications that involve requests between different domains (it often happened in a company I worked for).

Try setting CORS(app, resources={r"/*": {"origins": "*"}}) to be more direct about the configuration.

Oh, I remembered that if your Flask and the frontend are not using https it can give some problems too. I remember that mixing HTTP and HTTPS cause CORS errors quite frequently.

You can use this to test the CORS too https://www.test-cors.org/ to see if they are being delivered sucessfully.

Other than that…
Add more error handling?

This is what I had originally. Same exact error.

Oh ok. Do you think one of them would be using HTTP?

For what though? They all just say “access to __ from __ origin has been blocked…”

Probably, we had one of these scenarios where one of them was using HTTP and the other one was using HTTPS, after both start using the HTTPS the error stopped.

1 Like

How can I check that? I’m deploying with Cyclic but I’m using HTTPS to fetch it on the HTTPS replit.dev domain…

About the frontend, you can use the network tab in your browser tools to inspect the requests being made from your frontend. Just make sure that they are https request and that they are not being redirected to http.

About the Cyclic, you can verify that your Flask application deployed is accessible via an HTTPS url. For example, if you have an endpoint at /call , try accessing https://yourapp.cyclic.app/call

That’s what my JavaScript does right now. By the way, both the preflight and POST requests are on HTTPS on the frontend in the Network tab.

I tried that but I got status code 0 with no status text.

I might just use the API that was working before. Still a strange issue though

3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.