thinkdiff
thinkdiff

Reputation: 11

send multi object in response by expressjs

I have a simple middleware in expressjs

app.get("/" , function(req , resp , next){

/* object 1 with data */
var obj1 = [ 
             {"name":"linda","family":"kamelia"},
             {"name":"ama","family":"kandi"},
             {"name":"lucy","family":"lofa"}
           ];

 /* object 2 with data */
 var obj2 = [ 
             {"name":"kama","family":"kambril"},
             {"name":"soli","family":"sepani"},
             {"name":"sara","family":"fani"}
           ];

    resp.send("First: " + obj1 + "<br> Secoud: " + obj2 );
}); 

it show me this result in output:

First: [object Object],[object Object],[object Object]
Secoud: [object Object],[object Object],[object Object]

how can I print the real data from response in output?

Upvotes: 0

Views: 174

Answers (4)

Nimer Awad
Nimer Awad

Reputation: 4199

You can send them separately, like :

res.write(obj1);
res.write(obj2);
res.end();

Note: res.send() functions calls end() functions by default

Upvotes: 0

Amulya Kashyap
Amulya Kashyap

Reputation: 2373

See,

First of all instead of using res.send() use res.json().

Then, improve it by sending like this:

res.json({"obj1":JSON.Stringify(obj1), "obj2":JSON.Stringify(obj2)});

else you can try as well

res.json({"obj1":obj1, "obj2":obj2});

and on client end you can recieve it like this :

var data = JSON.Stringify(result); var obj1 = data[0].obj1 && var obj2 = data[0].obj2

Upvotes: 0

abdulbari
abdulbari

Reputation: 6232

That not gonna work in this format try this

resp.send({First: obj1 ,Secoud:  obj2});

Now you will get the object with two properties First and Second and access it with obj.First and obj.Second

Upvotes: 1

Atul Agrawal
Atul Agrawal

Reputation: 1520

Stringify the object

resp.send("First: " + JSON.stringify(obj1) + "<br> Secoud: " + JSON.stringify(obj2) );

Upvotes: 0

Related Questions