javascriptjqueryjsonnode.jsappjs

node.js - get value of json request


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);

Solution

  • 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);
    });