Nodejs & Express: How to send multiple Json variable from server to Client through response.send()

29.8k views Asked by At

I am developing an nodejs search application for itunes-search and searching some software information from my local database with express framework. The search module returns information like software name, music name through a single json variable. But now I also need Music artist details/ Software company name through another different json variable. I can simply return the song details with the bellowed code. In client sides:

$scope.search_music_data = function(data)
{
  var data="Hamdoon Soft";//Search my favourite artist name or band name
    $http({'method' : 'post', url: '/search', data: {'search_item' : data}}).
    success(function(data){ 
        $scope.artist_name = data; 
    }).
    error(function(data){ 
    })
    $scope.check = true;
}

Bellowed codes are in server sides:

In route.js

app.post('/search', search.search_music);

In search_music function currently this code is working:

ItemName="calculated data Json Data"
var response.send(ItemName);

But I also need send another calculated data like

  ItemName="calculated data Json Data"
  ArtistName="calculated data Json Data"
  var response.send(ItemName, ArtistName);

Or ItemName="calculated data Json Data" SoftWareCompnayName="calculated data Json Data" var response.send(ItemName, SoftWareCompnayName); Is it possible?I will really appreciate him/her if he/she can help me.

3

There are 3 answers

1
Md Nazmul Hossain On BEST ANSWER

Use this in server side code. I think this will help you. This is the example of multiple value sent from server to client.

res.send({artist: artist_details, music: music_details});

In client side :

you can access it data.artist & data.music from angular controller.

0
Wilson On

so you could pass an object to response.send method which that object will include your song and artist info.

var data = {
  song: ..,
  artist: ..
};

response.send(data);

I tried itunes-search but it throws an error when I got started using it, so I created my own module that do the same task as itunes-search.

This is my example using my own method getSongsAndArtistInfo which returns an object containing songs and artist info properties:

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

var itunes = require('./itunes');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.post('/search', function (req, res) {
  var searchItem = req.body.searchItem;
  itunes.getSongsAndArtistInfo(searchItem, function (err, result) {
    if (err) res.status(404).send(err);

    res.send(result);
  });
});

app.listen(4000, function () {
  console.log('server up and running at 4000 port');
});
0
APP On

you can have more than one res.write() but only one res.send()...

res.write("object")
res.write("object")
res.send()