gb_spectrum
gb_spectrum

Reputation: 2301

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

Upvotes: 1

Views: 8792

Answers (2)

Quentin
Quentin

Reputation: 944474

When you make a GET request, the data appears in the query string (of the URL in the request headers). It doesn't appear in 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;

Upvotes: 1

Hieu Tran
Hieu Tran

Reputation: 364

I think var userInputForm = $('#userInputForm.val()') will get error or get wrong data..This may be the reason for the error. Due to userInputForm may not be a string and concatenate with userInput= Actually it is bad data. And for the data in ajax, you should modify data from data: "userInput=" + userInputForm, to:

data: {
  userInput: userInputForm
},
dataType: "json"

And var userInputForm = $('#userInputForm.val()')

to var userInputForm = $('#userInputForm').val();

At last, you could modify as bellow, I believe it works:

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

Upvotes: 0

Related Questions