Nathan Modern Nathan Modern - 1 month ago 11
Ajax Question

AJAX and Node JS/Express post not sending or receiving data

I am new to Node and I am trying to use app.post, everything works fine including the console log whenever the action is executed but it does not receive the data sent by the AJAX from main.js.

Here is a snipper of main.js which sends it:

$.ajax({
type: 'POST',
data: '{"title":'+ this.messageInput.value +'}',
url: 'http://localhost:3000/send'
});


Here is my config.js which should be receiving the data:

app.post('/send', function(req, res) {
console.log(req.body);
console.log('Send button clicked');
});


I am using bodyParser with express. So that is why I am using req.body. When I console log req.body I get undefined. When I console log req, I get a list of data but not what I sent.

I hope someone can help!

Answer

It's good that you are using body-parser, but have you defined a JSON parser in your app?

You didn't paste all of your code so add this if you don't already have it:

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// create application/json parser --> This is probably what you are missing
var jsonParser = bodyParser.json()

// POST /api/users gets JSON bodies --> Note how we use a jsonParser in our app.post call
app.post('/send', jsonParser, function (req, res) {
  console.log(req.body);
  console.log('Send button clicked');
})

Also, instead of constructing your data manually, just create an object and send it (remember JSON is short for - Java Script Object Notation)

var myData = {};
myData.title = this.MessageInput.value;

Then in your Ajax code, just use myData:

$.ajax({
    type: 'POST',
    data: myData,
    url: 'http://localhost:3000/send'
});

Note: most of this example is taken straight from the body-parser Github Page, it has plenty of well documented examples so if you're not sure how to use the module, check it out

Comments