FrontEnd this gets the name, age, city puts it in a JSON format and sends it to localhost:5100/getJson which is my backend.
<form>
<div class="form-group">
<label for="text">Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter name" name="name">
</div>
<div class="form-group">
<label for="text">Age:</label>
<input type="text" class="form-control" id="age" placeholder="Age" name="age">
</div>
<div class="form-group">
<label for="text">City:</label>
<input type="text" class="form-control" id="city" placeholder="Enter city" name="city">
</div>
<button onclick = "MyFunction()" id = "submitButton" type="submit" class="btn btn-default">Submit</button>
<p id = "demo">
</p>
<script>
function MyFunction() {
var name = document.getElementById("name").value
var age = document.getElementById("age").value
var city = document.getElementById("city").value
jsonRequest = {"name":name, "age":age, "city":city}
fetch('http://localhost:5100/acceptJson', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: jsonRequest
}).then(res => res.json())
}
</script>
my backend is a flask server in python.
Backend
app = Flask(__name__)
@app.route('/acceptJson',methods=['GET', 'POST'])
def acceptJson():
jsonData = request.json
name = jsonData['name']
age = jsonData['age']
city = jsonData['city']
postToDatabase(name,age,city)
return "Succesful"
if __name__ == '__main__':
app.run(host = "localhost", port = 5100)
Now when I make the same JSON post request using software like Postman it works, returns 200 and runs the script.
but when I do it through the code, it return 200 and doesn't run the script, so it's clearly something wrong with the POST in the javascript, but I do not understand where it's wrong.