问题返回对象
Issue returning object
我对学习如何在后端工作仍然很陌生,我已经 运行 解决了这个问题,它没有显示问题而是抛出错误(正在通过 Thunder Client 测试路由)这里是代码如下:
const express = require('express');
const router = express.Router();
// Question Data
const Questions = require('../../models/questions-data.json')
router.get('/', async(req, res) => {
try{
const question = await Questions.find()
return res.send(question)
}
catch(error){
return res.status(500).send({"error": error})
}
})
module.exports = router;
正如我所说,代码只是发送错误消息而不是显示问题,我不明白为什么,任何 help/tips 将不胜感激。
这里还有问题对象的结构:
question:string;
options:string[];
answer:string;
如果您的问题是 JSON 格式,find()
方法将抛出错误。 find()
方法用于数组,而不是对象。
此外,您写的是 req.send(question)
而不是 res.send(question)
。
尝试:
return res.send(Questions)
如果是对象,看响应是否给出对象。
如果 Questions
是一个对象数组,并且你想用 find
对其进行操作,你应该给出一个条件,该条件将 return 匹配该条件的第一个元素。
return res.send(questions.find(element=>element.someKey === 'someValue'))
尝试在 .find 中添加大括号
.find({})
我对学习如何在后端工作仍然很陌生,我已经 运行 解决了这个问题,它没有显示问题而是抛出错误(正在通过 Thunder Client 测试路由)这里是代码如下:
const express = require('express');
const router = express.Router();
// Question Data
const Questions = require('../../models/questions-data.json')
router.get('/', async(req, res) => {
try{
const question = await Questions.find()
return res.send(question)
}
catch(error){
return res.status(500).send({"error": error})
}
})
module.exports = router;
正如我所说,代码只是发送错误消息而不是显示问题,我不明白为什么,任何 help/tips 将不胜感激。
这里还有问题对象的结构:
question:string;
options:string[];
answer:string;
如果您的问题是 JSON 格式,find()
方法将抛出错误。 find()
方法用于数组,而不是对象。
此外,您写的是 req.send(question)
而不是 res.send(question)
。
尝试:
return res.send(Questions)
如果是对象,看响应是否给出对象。
如果 Questions
是一个对象数组,并且你想用 find
对其进行操作,你应该给出一个条件,该条件将 return 匹配该条件的第一个元素。
return res.send(questions.find(element=>element.someKey === 'someValue'))
尝试在 .find 中添加大括号
.find({})