【发布时间】: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