简体   繁体   中英

JSON Post request is showing 200 success, but script is not executing

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.

The problem seems to be related to your front-end. In the following answer, I assume your form is submitted by "MyFunction".

In this line of HTML:

<button onclick = "MyFunction()" id = "submitButton" type="submit" class="btn btn-default">Submit</button>

The button is a submit type button. When you click the button, the browser submits the form as usual. With no "action" attribute in the tag, the request is submitted to the webpage you open ie no request was sent to the back-end.

The solution can be found in this question: Form not submitting with JS . However, I would suggest another method to do so.

You may add "event.preventDefault();" before you call the function of handling the request or add it to the beginning of the function to stop the form from being submitted automatically in a traditional way.

<button onclick = "event.preventDefault();MyFunction()" id = "submitButton" type="submit" class="btn btn-default">Submit</button>

The reason why to use preventDefault is that it only stop the browser default behavior while other solution (return false) stop the event propagating the DOM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM