Nodejs请求 - 无法读取属性' forEach'未定义的

时间:2016-07-03 09:02:35

标签: javascript node.js drupal request

我在http://blog.openlucius.com/en/blog/headless-drupal-nodejs-part-33-express-js-and-drupal-api-integration跟随无头Drupal教程,但我的经验是Drupal方面而不是Node方面,所以现在有些东西坏了我不知道如何解决。< / p>

启动应用时出错:

/Library/WebServer/Documents/uno-fe/hellotest.js:23
blogsdata_all.blogs.forEach(function(item){
                   ^

TypeError: Cannot read property 'forEach' of undefined
    at Request._callback (/Library/WebServer/Documents/uno-fe/hellotest.js:23:24)
    at Request.self.callback (/Library/WebServer/Documents/uno-fe/node_modules/request/request.js:200:22)
    at emitTwo (events.js:87:13)
    at Request.emit (events.js:172:7)
    at Request.<anonymous> (/Library/WebServer/Documents/uno-fe/node_modules/request/request.js:1067:10)
    at emitOne (events.js:82:20)
    at Request.emit (events.js:169:7)
    at IncomingMessage.<anonymous> (/Library/WebServer/Documents/uno-fe/node_modules/request/request.js:988:12)
at emitNone (events.js:72:20)
at IncomingMessage.emit (events.js:166:7)

我的hellotest.js看起来像:

var express = require('express');
var app = express();
var routes = require('./routes/index');
var request = require('request');
var blogsurlall = "http://www.pickingorganic.org/blogsexportall";

app.set('view engine','ejs');

var server = app.listen (2000, function(){
   console.log('Waiting for you on port 2000');
});

request({
  url:blogsurlall,
  json:true
}, function(error, response, body){
  if (!error && response.statusCode===200) {
      blogsdata_all = body;
  }

  var blogs = [];

blogsdata_all.blogs.forEach(function(item){
    blogs = blogs.concat(item);
});

  app.locals.blogsdata = blogs;
})

app.use('/', routes);

我假设这与节点请求没有从“来源”获取json有关。网站正确,这就是为什么博客var是空的。不知道出了什么问题 - 任何帮助都非常感谢!

1 个答案:

答案 0 :(得分:2)

您应该在console.log中查看响应正文,看看它是什么样的。它是空的吗?

据我所知,网址是正确的,响应是:

[{"title":"second post","created":"2016-06-30T15:49:17+08:00","field_blog_image":"  \n\n","path":"\/node\/2","created_1":"30 2016 Jun","body_1":"some content","body":"some content","uid":"","user_picture":""},{"title":"first post","created":"2016-06-28T21:56:52+08:00","field_blog_image":"  \n\n","path":"\/node\/1","created_1":"28 2016 Jun","body_1":"woot","body":"woot","uid":"","user_picture":""}]

如果是这样,你应该这样做你的forEach:

blogsdata_all.forEach(function(item){
    blogs.push(item);
});

因为响应主体是一个对象数组。如果响应是这样的话,你尝试循环它的方式是正确的:

{"blogs":[{"title":"second post","created":"2016-06-30T15:49:17+08:00","field_blog_image":"  \n\n","path":"\/node\/2","created_1":"30 2016 Jun","body_1":"some content","body":"some content","uid":"","user_picture":""},{"title":"first post","created":"2016-06-28T21:56:52+08:00","field_blog_image":"  \n\n","path":"\/node\/1","created_1":"28 2016 Jun","body_1":"woot","body":"woot","uid":"","user_picture":""}] }

此外,您不必循环浏览将博客文章推回到新的数组中,您可以直接使用:

app.locals.blogsdata = blogsdata_all;