0

I have a python script which is a flask RESTApi:

from flask import Flask from flask_cors import CORS api = Flask(__name__) CORS(api) @api.route("/api/stopService", methods=['POST']) def startService() return { "MSG": "OK" } if __name__ == '__main__': api.run(port=8000) 

Now I want to make a request with angular using this code:

this.http.post('http://localhost:8000/api/stopService', {}).subscribe((res: any) => { }); 

It's just a simple button that when I click on, it triggers the request. but I get this error:
error

And if I click on the button again It's OK and I have the response.

Here is the flask log:
log

First line is when I get the CORS error, and the second and the third one is the OK response.

Edit 1
I changed my flask code to this but still no luck:

from flask import Flask api = Flask(__name__) @api.route("/api/stopService", methods=['POST']) def startService() return { "MSG": "OK" } @api.after_request def addHeaders(response): response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', 'Content-Type') return response if __name__ == '__main__': api.run(port=8000) 
3
  • Try to remove the empty object {} in your Angular post. Commented Apr 5, 2022 at 15:20
  • @MikeOne well that's required Commented Apr 5, 2022 at 16:30
  • @MikeOne, I replaced the empty object with null, and it got fixed. please send an answer so I can accept it Commented Apr 6, 2022 at 10:22

1 Answer 1

1

The problem is that angular runs on port 4200 and you try to do a call on port 8000. For the browser those are two different domains and therefore you get a cors error.

If you want to get it work on localhost, you have to add cors headers to the response in your python script:

Access-Control-Allow-Origin: http://localhost:4200 
Sign up to request clarification or add additional context in comments.

3 Comments

I'm using flask_cors
Try to add @cross_origin() below @api.route. According to documentation of flas_cors this should solve your problem
I did that, nothing changed

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.