0

I am sending a json object to my node server in java. I want to display the value in server console. On server console i am getting undefined. How to get the JSON object and parse it in nodejs using express.

Java Code

        try
            {
               HttpClient client = new DefaultHttpClient();
               HttpPost post = new HttpPost("http://example.com:3000/");
               JSONObject msg = new JSONObject();  Log.e("data",code);
               msg.put("data", code);
               HttpEntity entity = new StringEntity(msg.toString());
               BufferedReader reader = new BufferedReader(new   
               InputStreamReader(client.execute(post).getEntity().getContent()));
               String response = reader.readLine();
               Log.e("response", response);

            }
            catch(Exception e)
            { Log.e("",e.toString());
            }

Node Server

var express = require("express");
var http=require("http");
var app = express();
app.use(express.bodyParser());
app.post("/", function(request, response)
{


    response.send(JSON.stringify({success: true}));
    var token = request.body.data;
    console.log(token);


});
app.listen(3000);
3
  • 1
    You don't appear to be attaching the msg or entity to the post request or client. Commented Jun 6, 2014 at 14:39
  • can u correct it Jonathan ?? Commented Jun 6, 2014 at 14:41
  • I hv corrected it..! Anyways thanks Jonathan for pointing it..! Just after i posted my query i realized it. Commented Jun 6, 2014 at 15:40

2 Answers 2

1

You forgot to attach entity to your post request.

 try
        {
           HttpClient client = new DefaultHttpClient();
           HttpPost post = new HttpPost("http://example.com:3000/");
           JSONObject msg = new JSONObject();  Log.e("data",code);
           msg.put("data", code);

           // modified code below
           HttpEntity entity = new StringEntity(msg.toString(), ContentType.create("application/json"));
           post.setEntity(entity);

           BufferedReader reader = new BufferedReader(new   
           InputStreamReader(client.execute(post).getEntity().getContent()));
           String response = reader.readLine();
           Log.e("response", response);

        }
        catch(Exception e)
        { Log.e("",e.toString());
        }
Sign up to request clarification or add additional context in comments.

1 Comment

yeah..! i just realized it. Anyways thanks a lot..! :)
1

Have you tried using:

var bodyParser = require('body-parser');
app.use(bodyParser.json());

This requires you to install the body-parser package:

$ npm install body-parser

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.