0

I am creating a webhook in Python that will receive data from an HTML form and will save that as a JSON file. But When I am doing POST from HTML, it shows the following error.

form.html:1 Access to XMLHttpRequest at 'http://localhost:5000/webhook/' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I looked for this in other threads, and then I came across flask_cors and then I modified the Flask app accordingly as:

from flask_cors import CORS, cross_origin
from flask import Flask, request, abort

app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
@app.route('/webhook', methods=['POST'])

def webhook():
    if request.method == 'POST':
           print(request.json)
           return '', 200
    else:
        print("bad data")

if __name__ == '__main__':
    app.run(debug=True)

But even after doing this, it is still not able to complete the POST request. I still get same error and at this point I have no idea want to do next or how to fix it.

JavaScript's code in the HTML form:

<script>
document.getElementById("prev").addEventListener("click", myFunction);

function myFunction() {

form = document.getElementById("main");

document.querySelector(".loading").style.display = "block";
  var data = {};
  for (var i = 0, ii = form.length; i < ii; ++i) {
    var input = form[i];
    if (input.name) {
      data[input.name] = input.value;
    }
  }

var http_request;
http_request = new XMLHttpRequest();
http_request.onreadystatechange = function () { /* .. */ };
http_request.open("POST", "http://localhost:5000/webhook/");
http_request.setRequestHeader("Content-Type", "application/json");
http_request.send(JSON.stringify(data));

document.querySelector(".loading").style.display = "none";
}
</script>

Need help with this. Thanks.

  • Does this answer your question? [Solve Cross Origin Resource Sharing with Flask](https://stackoverflow.com/questions/26980713/solve-cross-origin-resource-sharing-with-flask) – rfkortekaas May 17 '21 at 18:04
  • No it doesn't help. But I now switched to jQuery. Sending POST data via Ajax and it works. Only JavaScript XHR doesn't work. –  May 17 '21 at 19:11

0 Answers0