Sean Burt
Sean Burt

Reputation: 1

Node.js & Express: Pushing to array results in "[object Object]"

I am new to web development and am taking a course for it. I am designing a test web server before I challenge the main project. For this test I am trying to take the value from a text block, and append it to a response section, all while making it so I do not lose data when I refresh the page.

Currently when I press the button, it appends: [object Object][object Object][object Object]

Below are my 3 files for this application

First is index.html:

<html>
<head>
    <title> Website Test </title>
</head>
<body>
    <h1> Website Test </h1>
    <p> press the button </p>
    <input type="text" id="input_block">
    <button id="test_button" onclick="sendData(document.getElementById
                ('input_block').value)"> Press Me Now </button>
    <p id="response"></p>

    <script type="text/javascript" src="myScript.js"></script>
</body>
</html>

Next is StaticServerProgram:

var express = require("express");
var bodyParser = require("body-parser");

var app = express();

app.use(bodyParser.json());

app.use(express.static('public'));

var myData = [];

app.get("/data", function(req, res){
    console.log(req.body);
    res.json(myData).ProjectName;
});

app.post("/data", function (req, res){
    console.log("POST Request to: /");
    console.log(req.body);
    res.send(req.body);
    myData.push(req.body);
});

app.listen(3000, function() {
    console.log("listening on port 3000");
})

Last is script.js:

function getData() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "/data", true)
    xhr.send();

    xhr.onreadystatechange = function(){
        if (xhr.readyState == 4 && xhr.status == 200){
            // got a response
            console.log(xhr.responseText);

            var arr = JSON.parse(xhr.responseText);
            console.log(arr);

            var s = "";
            for (var i = 0; i < arr.length; i++) {
                s+=arr[i];
            }

            document.getElementById("response").innerHTML = s;

        }
    };
}
function sendData(project_name){
    console.log("sending POST to /data");
    var obj = { ProjectName : project_name, ActivityName : "bites" };
    var postXhr = new XMLHttpRequest();
    postXhr.open("POST", "/data", true);
    postXhr.setRequestHeader("Content-type", "application/json");
    postXhr.send(JSON.stringify(obj));
    getData();
}
getData();

Any response to this issue would be greatly appreciated. If there is something someone sees that could be a problem in the future please comment. Thanks!

Upvotes: 0

Views: 4046

Answers (2)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123423

The appearance of [object Object] means that you're converting objects to strings.

That likely occurs client-side with s+=arr[i]:

var s = "";
for (var i = 0; i < arr.length; i++) {
    s+=arr[i];
}

To display an plain Object, you'll have to find or create something to format it. One option is to convert them back to JSON:

s+=JSON.stringify(arr[i]);

Or, access an property of the objects that isn't another object.

s+=arr[i].ProjectName;

Also, this line server-side doesn't do what you may have been expecting:

res.json(myData).ProjectName;

If you want to send only the project names to the client, you'll have to iterate over the array and create another. You can do that with .map().

res.json(myData.map(d => d.ProjectName));

Upvotes: 1

Duncan
Duncan

Reputation: 226

The response you are receiving is an array of Objects. You need to select the properties inside of this object to display the data.

for (var i = 0; i < arr.length; i++) {
 s+=arr[i]['ProjectName'];
}

Will attach the response to your element.

Upvotes: 0

Related Questions