4

I send array of strings from the server:

Node.JS + Express.JS

app.get('/url', function (req, res) {
    res.send(["item1", "item2", "item3"]);
})

But on the frontend I'm receiving array of objects:

Angular.JS

SomeResource.query(function (data) {
    console.log(data);
});

In Console

0: Resource
0: "i"
1: "t"
2: "e"
3: "m"
4: "1"
$$hashKey: "008"
__proto__: Resource
1: Resource
0: "i"
1: "t"
2: "e"
3: "m"
4: "2"
$$hashKey: "009"
__proto__: Resource
2: Resource
0: "i"
1: "t"
2: "e"
3: "m"
4: "3"
$$hashKey: "00A"
__proto__: Resource

Why this is happening? How can I receive same array on frontend? THanks

user3162402
  • 743
  • 1
  • 7
  • 7

1 Answers1

1

It's because MIME does not support JavaScript Array type data, unfortunately.

The content types defined by MIME standards are also of importance outside of email, such as in communication protocols like HTTP for the World Wide Web. HTTP requires that data be transmitted in the context of email-like messages, although the data most often is not actually email.

Use JSON.

You can confirm on browser debugger console(such as Firebug) or node console.

var json = JSON.stringify(["item1", "item2", "item3"]);
->undefined

JSON.parse(json);
->["item1", "item2", "item3"]

so, on server side

app.get('/url', function (req, res) {
    res.send(JSON.stringify(["item1", "item2", "item3"]));
})

and JSON.parse the data on client side to get the array.

  • unfortunately it's not worked. I updated server and client sides. Now I have error on console: `SyntaxError: Unexpected token o`. It pointed to `JSON.parse` place of code. Also array which came from server looks the same after I stringified it on serverside. – user3162402 Feb 13 '14 at 20:51
  • Probably,you know well that you can send "some string" from server to client. What we are talking about here is just send "JSON.stringified Strings" from server to client. And we know how to convert Array to JSON strings = `JSON.strigify` , and String to Array = `JSON.parse`. Perhaps, you also need https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent ,since it include double quotaion mark. –  Feb 13 '14 at 21:41
  • http://stackoverflow.com/questions/6807180/how-to-escape-a-json-string-to-have-it-in-a-url see this. –  Feb 13 '14 at 21:43
  • Thanks. But `$resource service expects a response that can be deserialized as an array, receives an object, or vice versa.` So now Angular throws error that it cant parse response – user3162402 Feb 13 '14 at 22:10
  • It's an Angular.JS error I presume. Here I presented the whole factors to send JSON array from server to client, but since I don't use Angular.JS, can't help the rest. –  Feb 13 '14 at 22:15