【问题标题】:nodejs why is my code returning [object Object] instead of an array?nodejs为什么我的代码返回[object Object]而不是数组?
【发布时间】:2021-01-29 09:47:22
【问题描述】:

所以我正在建立一个网站并使用 nodejs 进行一堆 api 调用并填充所有信息。我有一个主页,其中有一个侧边栏,人们可以按“类别”进行排序。但是当我运行我的代码而不是在 html 中显示的类别时,我得到[object Object]。我已经尝试了很多东西,但它仍然只返回[object Object]。这是代码:

index.js

const express = require('express')
const router = new express.Router();
const categoriesFunction = require('../controllers/categories')
// get index page
router.get('', async (req, res) => {
    let requestString = '/apps'
    allApps = await openChannelRequest(requestString, req, res)

    await res.render('index', {
    categories: categoriesFunction,
  // this is where I try to add the categories to the homepage
})
})

这是我获取所有类别数据并存储它的控制器。我很确定我可以在 index.js 页面中执行此操作,但几周前当我开始执行此操作时,出于某种原因我制作了控制器。如果这不是最好的方法,请告诉我。

categories.js

const express = require('express')
const app = express()
var request = require('request');
var categoricalNames = []
var options = {
  'method': 'GET',
  'url': 'a working url',
  'headers': {
    'Authorization': 'working authorization'
  },
  'contentType': 'application/json'
};

var categoriesFunction = async() => request(options, function (error, response) {
return new Promise(function(resolve, reject){
  console.log('inside categories function')
  var categoryName = ''

  if(error || !response)
     {
        // report error
        reject(new Error('Try Again'));
     }
     else
     {
        //process response
        var body = JSON.parse(response.body); 
        var jsonResponse = body.values
        jsonResponse.forEach(function(obj) {
           // console.log(obj.label)
            categoryName = obj.label
           // JSON.stringify(categoryName)
            categoricalNames.push(categoryName)
        });
        categoricalNames.push({categoryName});
      //  console.log(categoricalNames)
        // report success
        JSON.stringify(categoricalNames)
        resolve(categoricalNames);
     }
})

});

module.exports.getPlaceDetails = categoriesFunction;

有一段时间我认为我的代码不起作用,但我的 categoriesFunction 函数中的 console.logs 显示数组正在正确填充。它只是没有被正确地推送到索引。在 index.js 页面上尝试该方法对我没有任何作用。仍然只是得到[object Object]。不太清楚为什么。谁能给我解释一下?

谢谢!

【问题讨论】:

  • [object Object] 是当您使用需要字符串的对象时得到的。
  • @Barmar 那么我怎样才能让它返回呢?特别是一个数组
  • 你能弄清楚它在哪里变成了[object Object]吗? response.body 是什么?
  • @evolutionxbox 我不知道它在哪里变成[object Object]。当函数完成时,我可以将一个数组输出到控制台,所以我不确定它发生在哪里。 response.body 是一个大的 json 对象
  • 您可以使用控制台日志或开发工具找出[object Object] 的位置吗?

标签: javascript node.js arrays express promise


【解决方案1】:

我知道我需要做什么。基本上需要编写一个更干净的 Promise 并确保不返回数组而是 resolve 数组。并且还需要在 index.js 中有一个变量 awaits categoriesFunction() 的结果

这就是 index.js 现在的样子

const express = require('express')
const router = new express.Router();
const categoriesFunction = require('../controllers/categories')
// get index page
router.get('', async (req, res) => {
    let requestString = '/apps'
    allApps = await openChannelRequest(requestString, req, res)

    const thing = await categoriesFunction()
    // this is important cause the method needs to be called before its inserted
    await res.render('index', {
        categories: thing,
  // this is where I try to add the categories to the homepage
})
})

这是 categories.js 文件的样子

let categoriesFunction = function() {
return new Promise(resolve => 
request(options,
  (error, response) => {
    var categoryName = ''
    var body = JSON.parse(response.body); 
    var jsonResponse = body.values
    jsonResponse.forEach(function(obj) {
        categoryName = obj.label
        JSON.stringify(categoryName)
        categoricalNames.push(categoryName)
    });
    console.log(categoricalNames)
    resolve(categoricalNames)
   // now that this is resolved it can be returned 
  }
  ))
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    相关资源
    最近更新 更多