为什么在使用res.send()时express.js返回一个空数组? [英] Why does express.js return an empty array when using res.send()?

查看:50
本文介绍了为什么在使用res.send()时express.js返回一个空数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含键和值对数组的对象.

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' ]

当我在应用程序中调用res.send(myObject)时,我得到以下信息:

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
[]

我希望它发送myObject的内容,而不仅仅是"[]".

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

如果我将代码更改为res.send('string'),则会得到以下信息:

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

推荐答案

我遇到了同样的问题,尽管在console.log中很好地显示了填充的对象"作为空数组返回.

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)

=> [ ]

最好将结果变量描述为"具有属性的空数组"而不是对象,因此, res.send()不会返回值>.

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().

使用花括号将变量初始化为对象:

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 }

解决方案2

将结果转换为对象,然后返回如下:

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 }

这篇关于为什么在使用res.send()时express.js返回一个空数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆