Node v0.4.12中,

var http = require('http');

var options = {
  host: 'example.com',
  port: 80,
  path: 'example.aspx'
};

var req = http.request(options, function(res) {
  var result = '';
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    result += chunk;
  });

  res.on('end', function () {
    var jsonStr = JSON.stringify(result);
    var data = JSON.parse(jsonStr);

    console.log(data['Date']);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

req.end();


当我尝试console.log(data)时,它可以工作,但是console.log(data['Date'])返回undefined

JSON方案示例:

{“ Date”:“ 17.03.2012 15:28:47”,“ Categories”:[{“ ID”:1,“ Name”:“ Foo”,“ URLSlug”:“ foo”}]}}

我该如何解决这个问题?

谢谢!

最佳答案

如果我删除所有http请求代码,然后尝试解析并打印出解析的json的Date部分:

$ cat ex2.js
var data = JSON.parse('{"Date":"17.03.2012 15:28:47", "Categories":[{"ID":1,"Name":"Foo","URLSlug":"foo"}]}');
console.dir(data);
console.log(data['Date']);

$ node ex2.js
{ Date: '17.03.2012 15:28:47',
  Categories: [ { ID: 1, Name: 'Foo', URLSlug: 'foo' } ] }
17.03.2012 15:28:47

$


示例代码可以正常工作。您是否正在运行发布的文字代码?如果是,则错误可能是example.com没有返回您作为example.asp示例给出的JSON。对我来说,返回:

$ curl -I http://example.com/example.asp
HTTP/1.0 302 Found
Location: http://www.iana.org/domains/example/
Server: BigIP
Connection: Keep-Alive
Content-Length: 0


不是JSON,只是302重定向响应。您可能希望打印出完整的结果,以便查看它是否实际上是JSON或其他(在本例中为HTML):

$ cat example.js
var http = require('http');

var options = {
  host: 'google.com',
  port: 80,
  path: '/'
};

var req = http.request(options, function(res) {
  var result = '';
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('got data back!');
    result += chunk;
  });

  res.on('end', function () {
    console.log('request is done');
    console.dir(result);
    var jsonStr = JSON.stringify(result);
    var data = JSON.parse(jsonStr);
    console.log(data['Date']);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

req.end();


对我来说:

$ node example.js
got data back!
request is done
'<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">\n<TITLE>301 Moved</TITLE></HEAD><BODY>\n<H1>301 Moved</H1>\nThe document has moved\n<A HREF="http://www.google.com/">here</A>.\r\n</BODY></HTML>\r\n'
undefined


HTH,

凯尔

10-07 20:00
查看更多