Zoltán Schmidt
Zoltán Schmidt

Reputation: 1345

HTTP error 400 in AJAX POST request

I'm trying to make a very simple program that sends a variable to a server, to write out then.

According to Opera, it gets an HTTP 400 (Bad Request) at the end of Display().

.jade file

button(type='button', onclick='Display()') Display data

#modify
    p Lorem ipsum Display

script
    include main.js

main.js

function Display(){

    var xhttp = new XMLHttpRequest();
    var parameter = { "Name": "Katamori" };

    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            document.getElementById("modify").innerHTML = xhttp.responseText;
        }
    };

    xhttp.open("POST", "displayer.js", true);
    xhttp.setRequestHeader("Content-type", "application/json");

    xhttp.send(parameter);

};

displayer.js

function (req, res) {
    if (req.method == 'POST') {
        var jsonString = '';

        req.on('data', function (data) {
           jsonString += data;
        });

        req.on('end', function () {
            console.log(JSON.parse(jsonString));
        });

        req.on('error', function () {
            console.log("ERROR!");
        });
    }
}

I attempted to change parameter from JSON to simple text (with RequestHeader too), and in that case, I got an HTTP 404 error.

What's the reason and what's the proper solution?

Upvotes: 2

Views: 3283

Answers (2)

The Reason
The Reason

Reputation: 7973

Or you can even send it in another way, like below:

function display(){

  var http = new XMLHttpRequest();
  var params = "name=Katamori";

  http.onreadystatechange = function() {
      if (http.readyState == 4 && http.status == 200) {
          document.getElementById("modify").innerHTML = http.responseText;
      }
  };

  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http.open("POST", "/", true);
  http.send(params);

}

server-side code

app.post("/", function(req, res){
  var jsonString = '';
  req.on('data', function (data) {
      jsonString += data;
  });

  req.on('end', function () {
      console.log(jsonString); // name=Katamori
  });
});

w3schools

It works for me.

Thanks, i hope it will help you

Upvotes: 2

Musa
Musa

Reputation: 97717

You aren't sending JSON, serialize your data to JSON and send it

xhttp.send(JSON.stringify(parameter));

Upvotes: 4

Related Questions