首页 > 解决方案 > 从 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);
});

标签: javascriptnode.js

解决方案


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 秒......


推荐阅读