Why do I get a Error 400 when I want to post a JSON file HTTP REQUEST

时间:2019-01-18 18:35:55

标签: javascript json http object

This is the Code

function loadDoc() {
    var obj = {
        "username": "234zu",
        "subject": "qwertz",
        "content": "qw",
        "created_at": "2018-12-15 22:18:54",
        "updated_at": "2018-12-15 22:18:54"

    }
    var finish = JSON.stringify(obj)

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("demo").innerHTML = this.responseText;
        }
    };
   
    xhttp.open("POST", "url", true);
    xhttp.send("finish")
}
Ok now when I send the post I get a bad REQUEST But if I send a Post with post man it goes the post looks like { "id": 844, "username": "234zu", "subject": "qwertz", "content": "qw", "created_at": "2018-12-15 22:18:54", "updated_at": "2018-12-15 22:18:54" }

1 个答案:

答案 0 :(得分:1)

You are sending the string literal "finish" instead of the variable named finish having the request body stringified (var finish = JSON.stringify(obj)) . try changing to xhttp.send(finish)

Also the content type should be mentioned xhttp.setRequestHeader('Content-type', 'application/json') before the send is called.