N
N
Nikolay Baranenko2020-12-19 12:24:44
JavaScript
Nikolay Baranenko, 2020-12-19 12:24:44

How to correctly send json POST request?

Hello.

Probably a banal question, BUT you still have to ask

it, you need to send JSON

{"id": "1", "context1": "xyz1231sdfsdf"}

which will turn into an UPDATE in the PostgreSQL database

var json_context = {"id": "1", "context1": "xyz1231sdfsdf"}
        var xhr = new XMLHttpRequest();   // new HttpRequest instance
        var url = 'http://localhost:5000/test_update'
        xhr.open("POST", url, true)
        xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
        xhr.onreadystatechange = function() {
                if(xhr.readyState == 4 && xhr.status == 200) {
                    // alert(xhr.responseText);
                    console.log(xhr.responseText);
                }
        };
        xhr.send(JSON.stringify(json_context));
        console.log(xhr.responseText);


and there are no errors and no result...

CURL gives the result

$ curl --header "Content-Type: application/json" --request POST --data '{"id":"1","context1":"xyz123ddfg"}' http://localhost:5000/test_update


what is wrong with JS and how to solve this problem?

ps

backend on FLASK

@main_app.route('/test_update', methods=['GET', 'POST'])
def test_post():
    if request.method == "POST":
        print(request.is_json)
        content = request.get_json()
        print(content)
        print(content["id"])
        db.session.execute('update test set context1= :value1 where id= :value2',{'value1': content["context1"], 'value2': int(content["id"])})
        db.session.commit()
        return jsonify(content)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
abberati, 2020-12-19
@abberati

Use the modern convenient api, do not torture yourself and the browser
https://learn.javascript.ru/fetch#post-zaprosy

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question