javascript - 从 get 获取空数组
问题描述
当我要去 localhost:3000/api/categories 时,我得到一个空数组,但是当我记录我的产品时,对象内有很多数据。有人知道我在做什么错吗?谢谢!
let products = getData()
function getData() {
return fetch('some url',
{
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
).then(res => res.json())
};
app.get(('/api/categories'), (req, res) => {
products.then(console.log);
res.send(products);
products.then(console.log);
});
解决方案
products
是一个承诺。您不能通过res.send
.
相反,当你记录它时做你正在做的事情:使用then
:
app.get(('/api/categories'), (req, res) => {
products
.then(data => res.send(data))
.catch(error => {
// Send an error
});
});
请注意,您的代码在启动时获取产品一次,然后使用该静态产品集响应请求。
如果您想获得产品以响应客户的请求,请删除
let products = getData();
并将其放入get
处理程序中:
app.get(('/api/categories'), (req, res) => {
this.getData()
.then(data => res.send(data))
.catch(error => {
// Send an error
});
});
每次客户端调用您的服务器时都会重复请求。
当然,您可能会考虑一个中间立场,将数据保留并重用 X 秒......
推荐阅读
- r - R中的正则表达式和子字符串
- swift - 试图获取当前时间,但它给了我错误的时间 SWIFT 5
- java - 创建名为“org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0”的bean时出错
- prometheus - 从 Prometheus 导出数据点以通过第三方监控进行可视化
- c# - 扩展方法和动态变量
- php - 在 Laravel 中使用不同的密钥解密
- dictionary - 带传单的地图:地图上的两个点,在同一位置
- video-streaming - 将视频转换为包文件
- scala - 光滑的 DBIO.sequence 抛出没有为参数 cbf 找到隐含:compat.Factory
- javascript - 不能让协会续集