MonkeyOnARock MonkeyOnARock - 1 month ago 10
Ajax Question

Getting an AJAX GET request to work with Express.js

I am using node.js and Express.js on the back end, and am trying to make a server call from the client via AJAX.

So I have this POST request that works fine with AJAX:

node.js/Express.js:

app.post('/createNewThing', function(req, res) {
var userInput = req.body.userInput;
if (userInput) {
res.send('It worked!');
}
});


Client Side/AJAX request:

var userInputForm = $('#userInputForm.val()')
$.ajax({
url: "/createNewThing",
type: "POST",
data: "userInput=" + userInputForm,
dataType: "text",
success: function(response, status, http) {
if (response) {
console.log('AJAX worked!);
}
}
});


The
userInputForm
comes from an HTML form.

This POST request works fine. But I want to change this to a GET request. If I change
app.post
to
app.get
, and change
type
in the AJAX call to
GET
, I get this 500 error:

GET /createNewThing?userInput=
500

Answer

When you make a GET request, the data appears in the query string, not the request body. There is no request body.

When you try to read from the request body, you are trying to access a property of an undefined object, which triggers an exception and cause an internal server error.

This answer explains how to read a query string:

var id = req.query.id; // $_GET["id"]

So

var userInput = req.query.userInput;