我似乎无法返回想要返回的正确对象
我使用的是NodeJS,有些JS承诺会尝试通过特定的Web应用程序使用CMS。我试图从CMS API中获取一些数据,并能够console.log()数据,并且它可以很好地显示在控制台中。尽管当我尝试返回它时,它说该对象是未定义的。我不确定自己在做什么错。任何帮助将不胜感激!
module.exports = {
services: async function(){
fetch(
'/',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${token}`,
},
body: JSON.stringify({
query: `{
service {
serviceName
serviceImg {
url
}
}
}`
}),
}
)
.then(res => res.json())
.then((res) => {
return res.data;
})
.catch((error) => {
console.log(error);
});
},
}
就像我说的那样,当我执行“ console.log(res.data)”时,它表示未定义。
const records = require('../public/records');
//root route
router.get('/', async (req, res) => {
res.render("landing", {serviceRecord: records.services()});
console.log(records.services());
});
这是我的代码路由部分
function returning object
How I am using it in index.js
不用担心令牌变量是只读的!
回答如下:[services
需要return
fetch
。 Fetch返回一个Promise,因此应在调用render之前在路由中处理Promise和响应。
我似乎无法返回想要返回的正确对象
我使用的是NodeJS,有些JS承诺会尝试通过特定的Web应用程序使用CMS。我试图从CMS API中获取一些数据,并能够console.log()数据,并且它可以很好地显示在控制台中。尽管当我尝试返回它时,它说该对象是未定义的。我不确定自己在做什么错。任何帮助将不胜感激!
module.exports = {
services: async function(){
fetch(
'/',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${token}`,
},
body: JSON.stringify({
query: `{
service {
serviceName
serviceImg {
url
}
}
}`
}),
}
)
.then(res => res.json())
.then((res) => {
return res.data;
})
.catch((error) => {
console.log(error);
});
},
}
就像我说的那样,当我执行“ console.log(res.data)”时,它表示未定义。
const records = require('../public/records');
//root route
router.get('/', async (req, res) => {
res.render("landing", {serviceRecord: records.services()});
console.log(records.services());
});
这是我的代码路由部分
function returning object
How I am using it in index.js
不用担心令牌变量是只读的!
回答如下:[services
需要return
fetch
。 Fetch返回一个Promise,因此应在调用render之前在路由中处理Promise和响应。