1

How do I get the value of json data sent from client with ajax in node.js? I tried so many examples and q&a but still it's not working. I'm totally new to node.js so my question could be dumb. I got my codes below. Please kindly point me out where and what are wrong. I'm totally lost.

What i need is the value "TEST" from data of the json.

I tried req.body.data

Client [html]

$.ajax({
      type:"POST",
      url: 'http://localhost:8080/getFromDB',
      //data:JSON.stringify({"sql":"SELECT * FROM Track"}),
      data: '{"data": "TEST"}',
      success:function(data) {
        $('#disco').html(data);
      },
      error:function() {
        $('#disco').html('Error connecting to the server.');
      }
    });

node.js

var app   = module.exports = require('appjs');
var http  = require('http');
var url   = require('url');
var fs    = require('fs');

http.createServer(function (req, res) {

  var path = url.parse(req.url).pathname;
  var value;

  if(path == "/getFromDB") {

    // req = JSON.parse(req);
    // var testshit1 = parser(req.data);

    req.on('data', function (data) {
      value = JSON.parse(data);
    });

    // ------- e.o test -------

    res.writeHead(200, {
      'Content-Type': 'text/plain',
      'Access-Control-Allow-Origin' : '*',
      'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE'
    });
    res.end('value = ' + value);
  }

}).listen(8080);
Nerdar
  • 1,103
  • 2
  • 10
  • 23

3 Answers3

4

data in req.on('data', function(data) { ... }) is a Buffer, you need to convert it to a string first. Also, you could receive any number of data events that need to be put together to make up the request body. With those things in mind, the steps are:

  1. Create a variable to hold your request body.
  2. When you receive a data event on your req object, append the data you receive to the variable that holds your request body.
  3. When you receive an end event on your req object, convert your request body to an object with JSON.parse.

Something like this:

var body = ""; // request body

req.on('data', function(data) {
    body += data.toString(); // convert data to string and append it to request body
});

req.on('end', function() {
    value = JSON.parse(body); // request is finished receiving data, parse it
});

Also, you'll most likely only want to respond with res.writeHead, res.end, etc once you've received the entire request body, so do that in the request's end event handler:

req.on('end', function() {
    value = JSON.parse(body); // request is finished receiving data, parse it

    res.writeHead(200, {
      'Content-Type': 'text/plain',
      'Access-Control-Allow-Origin' : '*',
      'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE'
    });
    res.end('value = ' + value);
});
Mike S
  • 41,895
  • 11
  • 89
  • 84
  • hi @Mike S , the code you gave works! however, the value is now changed to 'undefined' to '[Object Object]. can help lend me any advice for this? ^_^ – Nerdar Sep 17 '14 at 07:14
  • 1
    Funny enough, you need to convert your JSON back in to a string when you call res.end(). Try: 'value = ' + JSON.stringify(value) – Mike S Sep 17 '14 at 07:33
  • omg it took me so long to find that out, I used to use `querystring.parse(body)` and it never worked, don't know what's the difference though :\ – shakram02 Dec 21 '17 at 21:14
0

Your value in node is an object. use him. Example:

req.on('data', function (data) {
      value = JSON.parse(data);
      console.log("SQL is " + value.sql);
    });
SlyBeaver
  • 1,272
  • 12
  • 22
0

I suggest you to use Local IP instead "localhost".

You can use getJSON() and then search into structure or if you know where is the value, access it directly:

$.getJSON('http://192.168.1.1:8080/getFromDB', function (data) {
         var myVar = data.features[0].TEST;
         });
kike
  • 4,255
  • 5
  • 23
  • 41