user2573690 user2573690 -3 years ago 104
Node.js Question

Ajax call to express route not working?

I am trying to make an ajax call from one of my javascript files to an express route within my Node.js application, note that the javascript file is also part of the same Node.js application.

The issue I am having is that the data passed to the route is always empty. I can see that the route is being called because my console.log shows an object in the req but that object is empty.

Here is my code for the ajax call:

$.ajax({
type: 'POST',
url: '/match',
contentType: 'application/json',
data: "test",
success: function(data) {
console.log("Successfully saved the matched beans to the user.");
}
}).done(function ( ) {
console.log("OK");
}).fail(function ( jqXHR, textStatus, errorThrown ) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});


And my route looks like this:

router.post("/match", middleware.isLoggedIn, function(req, res) {
console.log("Route Test1: " + req.body);
console.log("Route Test2: " + JSON.stringify(req.body));
});


In the first console.log of the route I get
Route Test1: [object Object]
and for the second console.log I get
Route Test2: {}
.

How do I access the data "test" which I passed to the route?

Thanks in advance for the help!

Answer Source

While "test" is valid JSON, it's not very informative and assuming you're using body-parser, I'm not sure if it's set up to handle raw strings.

Try

contentType: 'application/json',
processData: false,
data: JSON.stringify({data: 'test'})

and in your route,

console.log('Route Test1:', req.body.data)

Also make sure you're using the json() method from body-parser, ie

app.use(bodyParser.json())

Another problem you're running in to is that you are automatically converting req.body into a string in your console.log calls due to the concatenation.

Instead, try

console.log('Route Test1:', req.body)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download