0

js and node.js and I'm having some troubles with json response.I have a node.js server that performs a get to a REST api,and the json result must be sent to an angular client but when I try to read that json file,I obtain [Object,Object].I can't figure out what I am missing.Thanks for helping me. Json file response from the REST API:

[ { cityPK: { name: 'Lodi', region: 'Lombardia' } },
{ cityPK: { name: 'Frosinone', region: 'Lazio' } },
{ cityPK: { name: 'Roma', region: 'Lazio' } },
{ cityPK: { name: 'Tivoli', region: 'Lazio' } } ]

node.js file:

var http = require('http');
var request = require('request');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

app.post('/login',function(req,res){
    console.log("sono nella post "+req.body.username);
    var uid = req.body.username;
    var upwd = req.body.password;
    res.setHeader('Content-Type', 'application/json');
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Credentials", true);



    request({
        url: "http://localhost:8080/RestServiceAdmin/webresources/entities.city",
        method: "GET",
        json: true ,
        headers:[{'content-type': 'application/json'}] 
    }, function (error, response, body){
           if(!error & response.statusCode === 200){
               res.json(body);
           }
    });
});
    app.listen(9080,function(){
    console.log('Server running at http://127.0.0.1:9080/');
});

Angular client:

 var app = angular.module('myApp',[]);
        app.controller('myCtrl',function($scope,$http){
            $scope.check = function(data){
                var id = data.form.id;
                var pwd = data.form.password;
                console.log("utente è "+id+",password è "+pwd);
                var msg = {username: id,password: pwd};
                $http({
                    url:'http://localhost:9080/login', //senza niente qui,metti * in app.post()
                    method:"POST",
                    data: $.param(msg),
                    responseType: "application/json",
                    headers: {'Content-Type': 'application/x-www-form-urlencoded',
                              'Accept': 'application/json' 
                              }})
                        .then(function(response){

                            console.log("Server response "+response.data);
                    });
            };
        });

I think that "response.data" should give me the json file,while it returns me [Object,Object].What's wrong with me?

1 Answer 1

1

Solution

You're almost there!

Just need to change the + in your log statement to a ,.

like this:

console.log("Server response ", response.data);

Reason

The + operator will try to concatenate the object to a string, the object isn't a string so it calls the toString() function, which shows you [Object,Object], meaning that you have an object which contains an object.

When you use a comma it will inspect the object.

From the toString() documentation:

Every object has a toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString() method is inherited by every object descended from Object. If this method is not overridden in a custom object, toString() returns "[object type]", where type is the object type. The following code illustrates this:

Sign up to request clarification or add additional context in comments.

4 Comments

Ok this is totally new to me,thanks a lot.But with response.data now I get Array [Object,Object]. So I have to do response.data[i].cityPK.name and cycle to obtain all values.Is this the only way,right? Great thanks for saving my night!
Always use commas , to print object if you have a string before it. If you inspect the object you should be able to tell it's structure. and you shouldn't get [Object,Object]. For example try to print the object without concatenating it to a string I.e console.log(response.data);. Also have a look at JSON.stringify.
In fact by inspecting the element,I've seen that I've to enter into a cell and then take the value I want.Thanks a lot,now I've a clearer vision.
No problem :) Happy coding!

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.