1

Frontend API Code (fetch async JS):

export async function auth(username, password){
    const constUSER = username
    const constPASS = password
    const api_url_auth = "http://127.0.0.1:5000/login/" + constUSER + "/" + constPASS

    const response = await fetch(api_url_auth,{
        method: "POST",
        headers:{
            'Access-Control-Allow-Origin':'*'
        }
    });

    
    const data = await response.json();
    return data
}

Backend API Code (flask Python):

@beapi.route("/login/<username>/<password>", methods = ['POST'])
    @cross_origin(supports_credentials=True) 
    def login (username, password):
 

        global userdetails
        global account_id
        #Find The Data inside the Collection Check's if the username is available
        userdetails = database.get_Account_LogIn_Details(username)
        

        databasepwr = userdetails[2] #password Database
        account_id = userdetails[0] #Account Id
        pwr = password

        dict_true = {"response": "True"}

        dict_false = {"response": "False"}
        
        dict_NF = {"response" : "NF"}
        
        #Returns True or False Verification Process
        if userdetails != "e0101db":
                if pwr == databasepwr:
                        database.update_Time_In(account_id= account_id, date=date, time=time )
                        return jsonify(dict_true)
                else:
                        return jsonify(dict_false)


        else:
                return jsonify(dict_NF)

The Error: Error

What I did so far:

added CORS(myAPI) on the backend and added mode:"no-cors"on the frontend. None work so far and what I added in my question so far is the closest (I think) I've gotten to solving this problem

  • 1
    `Access-Control-Allow-Origin` is a response header, rather thna a request one, and `*` is not a valid value. When you make the request, what do the response headers look like? You can check w/ the chrome network tab or something like postman. – CollinD Oct 15 '22 at 16:31
  • oh wait it isnt? i just copy pasted that snip of code also the response headers are Connection: close Content-Length: 16781 Content-Type: text/html; charset=utf-8 Date: Sat, 15 Oct 2022 16:30:46 GMT Server: Werkzeug/2.2.2 Python/3.10.7 Connection: close Content-Length: 16781 Content-Type: text/html; charset=utf-8 Date: Sat, 15 Oct 2022 16:30:46 GMT Server: Werkzeug/2.2.2 Python/3.10.7 – Therone Almadin Oct 15 '22 at 16:45
  • yeah I'm not super familair with flask, it seems like from their docs you have this set up right, hopefully someone w/ more knowledge can help out :). But yeah the goal is that when you send a request from `localhost:3000` to your API, it should respond with `Access-Control-Allow-Origin: localhost:3000` (usually this is pulled from the request's `HOST` header if you want to emulate a kind of wildcard. – CollinD Oct 15 '22 at 16:48
  • hopefully, I have been stuck on this for a day now – Therone Almadin Oct 15 '22 at 17:02
  • @CollinD `*` _is_ a valid value, unless you also want to send credentials. Quote from the [docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin): _For requests without credentials, the literal value "`*`" can be specified as a wildcard; the value tells browsers to allow requesting code from any origin to access the resource. Attempting to use the wildcard with credentials results in an error._ – CherryDT Oct 15 '22 at 20:13
  • https://stackoverflow.com/questions/10636611/how-does-the-access-control-allow-origin-header-work#:~:text=Access%2DControl%2DAllow%2DOrigin%20is%20a%20CORS%20(cross,is%20accessible%20to%20certain%20origins. it's not for popular browsers including firefox and chrome. See comments here – CollinD Oct 15 '22 at 20:14
  • @CollinD I use it for many years with no issues. Also the [compatibility table](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin#browser_compatibility) shows full support in all modern browsers. The link you shared also doesn't indicate otherwise... It says the same as I said: _**In case of using an authentication**, `Access-Control-Allow-Origin` does not accept the `*` in some browsers (FF and Chrome AFAIK)._ There is no HTTP auth involved in the OP's question. – CherryDT Oct 15 '22 at 20:16
  • @CollinD Even though it's not correct that `*` is generally invalid (only with credentials), this made me realize that the OP was actually setting `supports_credentials=True`! Thanks, this may very well be the cause... – CherryDT Oct 15 '22 at 20:27
  • Good to know, cherry. I probably experienced some issue years back and just logged that as the-way-of-things. Appreciate it! – CollinD Oct 15 '22 at 20:31

2 Answers2

1

You need to add the allow origin header in the response headers, the server supposes to add the CORS header

In your code it's in the request header instead.

The flow will look like this: enter image description here

You have HTTP POST request with JSON content type that's means you need

  • Access-Control-Allow-Origin header - your client origin
  • Access-Control-Allow-Methods header - POST
  • When you use the Access-Control-Allow-Credentials the origin cannot be *

You can read more about CORS mechanism here - https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

To enable CORS for your website in your flask server you can use the Flask CORS lib - https://flask-cors.readthedocs.io/en/latest/

ofir elarat
  • 235
  • 1
  • 9
  • That library is probably already in use, note line 2 in the OP's backend code which adds the `cross_origin` decorator. – CherryDT Oct 15 '22 at 20:31
  • Yes, but the problem their is adding the allow credentials header without specify the allow origin header (the default is * what makes the problem) – ofir elarat Oct 15 '22 at 22:29
0

If you don't use HTTP auth credentials (doesn't seem like you do), you don't need the support_credentials=True in your CORS configuration on the server (line 2 of the code you showed).

This will result in no origins being returned at all if you didn't specify origins because of the invalidity of * together with credentials.

If you set this to False or remove it, a header with origin * should be returned.

CherryDT
  • 25,571
  • 5
  • 49
  • 74