Reputation: 524
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:
And if I click on the button again It's OK and I have the response.
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)
Upvotes: 0
Views: 694
Reputation: 61
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
Upvotes: 1