This question already has answers here:
Closed 3 years ago.
Trying to understand how to send post requests to my backend (flask).
In my HTML I have 3 checkboxes and a submit button. My submit button returns a javascript array and I'm trying to send that javascript array to an api endpoint 'api/regions' which you can see below.
$(document).ready(function() {
$("#loadData").click(getChecked);
});
function getChecked() {
event.preventDefault();
var checkboxes = $(".form-check input[type=checkbox]:checked");
//toArray: convert checkboxes object to javascript array
var labels = checkboxes.toArray().map(checkbox => checkbox.value);
$.ajax({
url: 'api/regions',
type: "POST",
data: JSON.stringify(labels),
processData: false,
contentType: "application/json; charset=UTF-8",
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
}
In my app.py I have a route for my endpoint api:
@app.route('/api/regions', methods=['POST'])
def regions():
regions = request.json
with open("C:\\test.txt", 'w') as f:
f.write(regions)
if __name__ == "__main__":
app.run(debug=True)
I understand there is no return statement, I'm just trying to write the data I get from
regions = request.json
to a file. "C:\test.txt"
The error I'm getting when trying to do this is 500 which doesn't give me a lot to work with. I'm not sure if what I'm missing is on the front end or back end so hopefully someone could shed some light on where I'm going wrong.