Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No 'Access-Control-Allow-Origin' header on POST (Flask API) [duplicate]

I am working on my first API and so far I have been able to google for help, but I am stuck on this one:

My POST requests work fine on Postman, but when I try to use a form in my HTML to make a POST request, I get the following error:

Access to fetch at 'http://127.0.0.1:5000/api/v1/units' from origin 'http://localhost:63342' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

index.html:1 Uncaught (in promise) TypeError: Failed to fetch

The method in my Flask app:

@marshal_with(unit_fields)
def post(self):
    args = self.reqparse.parse_args()
    unit = models.Unit.create(**args)
    return unit, 201, {"Access-Control-Allow-Origin": "*",
                       "Access-Control-Allow-Methods": "POST",
                       "Access-Control-Allow-Headers": "Content-Type",
                       "Location": url_for("resources.units.unit", id=unit.id)}

The fetch call in Vue.js app:

addUnit: function() {
       fetch("http://127.0.0.1:5000/api/v1/units", {
           method: "POST",
           headers: {
               "Content-Type": "application/json"
           },
           body: JSON.stringify({
               name: document.querySelector("#unitName").value,
               faction: document.querySelector("#unitFaction").value
           })
       })
   }

Thank you for any advice how to get past it :)

like image 494
komret Avatar asked Oct 19 '25 14:10

komret


1 Answers

Amazing, thanks, Stephan! All it needed was:

from flask_cors import CORS

and

CORS(app, support_credentials=True)

in app.py!

like image 67
komret Avatar answered Oct 21 '25 04:10

komret