首页 > 解决方案 > Firebase 函数端点从服务器返回一个空对象,但在 localhost 中工作

问题描述

我正在使用 firebase 函数和 express JS 创建一个 API。在快递中,我有许多使用 Axios 从互联网获取数据的 GET 路由。除此之外,一个 GET 路由使用 Axios 和JSDOM 抓取一个站点并返回一个对象数组。

我正在使用 async-await 修饰符以异步方式运行代码。但是,所有其他端点都返回了正确的数据,但没有抓取一个。

从控制台,它实际上是在响应内部然后回调,但返回一个空对象。同样从 firebase 控制台,我知道它正在记录错误"Error: Request failed with status code 503Error"

代码:

index.js
//To get crypto news
app.get("/crypto-news", (req,res) => {
    return cryptoNews.getLatesCryptoNews().then(async(response) => {
        console.log("News arrived") //Which is actually logging in console
        return Promise.resolve(res.json({data: response}));
    }).catch(err => {
        console.log("Failed to fetch")
        return res.send("Failed to fetch from API");
    })
});

//Firebase 
exports.app = functions.https.onRequest(app);


cryptoNews.js

//Get nse equity data
async function getLatesCryptoNews() {

    try {
        let response = await axios({
            method: 'get',
            url: `https://tracemycode.com/`,
            json: true
        });

        if (await response) {
            const dom = new JSDOM(response.data);
            const document = dom.window.document;
            const posts = document.querySelectorAll("div.news-posts");

            //Check emptiness
            if (posts.length !== 0) {
                let data = [];

                console.log("Posts not empty"); //not loggin in console
                
                //Go through each node and get data
                posts.forEach(item => {
                    let time = item.querySelector('div.news-post-time p').textContent;
                    let title = item.querySelector('div.news-post-title h1').textContent;


                    //Push to array
                    data.push({
                        "title": (title !== null && typeof title === "string") && title,
                        "time":( time !== null && typeof time === "string") && time.substring(1, time.length - 1),
                    });
                });
                console.log("Sending data") //not logging in console
                return Promise.resolve(data);
            }
        }
    } catch (err) {
        console.error(err + "Error");
    }
}

exports.getLatesCryptoNews = getLatesCryptoNews;

我想知道为什么它在 localhost 而不是在 firebase 功能服务器中运行良好。

标签: javascriptnode.jsfirebasegoogle-cloud-functions

解决方案


推荐阅读