13

I have this object that contains an array of key and value pairs.

console.log(myObject);

[ 'askdasuni.com': '11111',
  'capsfrom2011.com': '22222',
  'defusionet.com': '33333' ]

When I call res.send(myObject) in my application I get the following:

< HTTP/1.1 200 OK
< X-Powered-By: Express
< Content-Type: application/json; charset=utf-8
< Content-Length: 2
< Date: Wed, 11 Mar 2015 18:15:41 GMT
< Connection: keep-alive
[]

I would expect it to send the contents of myObject, not just "[]".

If I change my code to res.send('string') instead, I get the following:

< HTTP/1.1 200 OK
< X-Powered-By: Express
< Content-Type: text/html; charset=utf-8
< Content-Length: 6
< Date: Wed, 11 Mar 2015 18:21:09 GMT
< Connection: keep-alive
< 
string
A.B
  • 17,478
  • 3
  • 28
  • 54

7 Answers7

15

I had the same problem, with a populated "object" being returned as an empty array, despite being nicely displayed with console.log.

Upon inspection I found that I had actually initialized an array, and then used it as if it was an object:

var myObject = [ ]
myObject['...'] = ...
...
res.send(myObject)

=> [ ]

The resulting variable is probably best described as "an empty array with properties" rather than an object, and as such the values were not returned by res.send().

Solution 1

Initialize the variable as an object, using curly braces:

var myObject = { }      <----- curly braces
myObject['...'] = ...
...
res.send(myObject)

=> { x : object-x, y : object-y, z : object-z }

Solution 2

Convert the result to an object before it is returned as follows:

var myObject = [ ]
myObject['...'] = ...
...
var myObject = [ ]
let obj = { }
for (var key in myObject) {
  obj[key] = myObject[key]
}
res.send(obj)

=> { x : object-x, y : object-y, z : object-z }
Philip Callender
  • 1,341
  • 1
  • 13
  • 21
4

try sending with

res.json(myObject)

res.json ensures that the response will have utf8 charset and application/json content-type

A.B
  • 17,478
  • 3
  • 28
  • 54
3

Don't be confused with res.json([body]), res.jsonp([body]), res.send([body]) all vary from each other and use it as and when you need it.

res.send([body])

Sends the HTTP response. The body parameter can be a Buffer object, a String, an object, or an Array.

res.json([body])

Sends a JSON response. This method is identical to res.send() with an object or array as the parameter. However, you can use it to convert other values to JSON, such as null, and undefined. (although these are technically not valid JSON)

So if you strictly want to send JSON response, best would be to use res.json(..)

Community
  • 1
  • 1
NarendraSoni
  • 2,020
  • 16
  • 23
1

You need to wrap your object in curly brackets, not square brackets as you are sending it as an object rather than an array. Key-value pairs must be wrapped in curly brackets in javascript.

1

see this answer: Why does a string index in a javascript array not increase the length size?

Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:

array.a = 'foo'; array['a'] = 'foo'; Those properties are not part of the "data storage" of the array.

e.g. use

{ 'askdasuni.com': '11111',
  'capsfrom2011.com': '22222',
  'defusionet.com': '33333' }
Community
  • 1
  • 1
Toskan
  • 11,184
  • 12
  • 75
  • 144
1

I faced similar issue. Although I can console log the data, the response would be empty. I figured out the Promise was not getting resolved, before response is sent. So I called .then on async function and returned the response from inside then call. That resolved the issue for me. Code will look like below.

router.get('/',(req,res) => {
    res.setHeader('Content-Type', 'application/json');
    getParallel().then(obj=>{res.json(obj);res.end()})
})
0

I didn't get any message from Console,get error "

Error: Network Error at createError"

from Axios's response.Then i think it was caused by CORS. The question was solved by adding below code:

app.use(function(req,res,next){
    res.header("Access-Control-Allow-Origin","*");
    res.header("Access-Control-Allow-Headers","Origin,X-Requested-With,Content- 
        Type,Accept");
    res.header("Access-Control-Allow-Methods","PUT,GET,POST,DELETE,OPTIONS");
})
Sociopath
  • 11,667
  • 16
  • 38
  • 61