如何解决在获取中将循环结构转换为JSON问题

问题描述 投票:2回答:1

我想通过提供用户名来获取存储库列表。下面是我到目前为止所做的。

router.get('/github/:username', (req, res) => {
    try {
        const url = `https://api.github.com/users/${req.params.username}/repos?per_page=5&sort=created:asc&client_id=${config.get('githubClientId')}&clientSecret=${config.get('githubSecret')}`;
        const headers = {
            "Content-Type": "application/x-www-form-urlencoded",
        };
        console.log(url);
        fetch(url, {
            method: 'GET',
            headers: headers,
        }).then(data => {
            if (data.status !== 200) {
                return res.status(404).send({
                    msg: 'No GitHub profile found'
                });
            } else {
                return data.json();
            }
        }).then(result => res.json(result));
    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server Error');
    }
})
  1. 当我在浏览器中使用动态创建的URL时,得到响应
  2. 当我传递有效的用户名时,我在测试API的Postman中获得了存储库
  3. 当传递无效的用户名时,出现以下错误
(node:18684) UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
    at JSON.stringify (<anonymous>)
    at stringify (E:\Connector\node_modules\express\lib\response.js:1123:12)
    at ServerResponse.json (E:\Connector\node_modules\express\lib\response.js:260:14)
    at fetch.then.then.result (E:\Connector\routes\api\profile.js:396:31)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:18684) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

有人可以告诉我如何解决此错误吗?我查看了很多资源,但找不到任何具体信息。

javascript node.js promise fetch
1个回答
0
投票

问题是第一个return res.status(404).send(…)回调中的then。然后,第二个then回调将尝试返回返回值的res.json(result)

您应该写

router.get('/github/:username', (req, res) => {
    const url = `https://api.github.com/users/${req.params.username}/repos?per_page=5&sort=created:asc&client_id=${config.get('githubClientId')}&clientSecret=${config.get('githubSecret')}`;
    const headers = {
        "Content-Type": "application/x-www-form-urlencoded",
    };
    console.log(url);
    fetch(url, {
        method: 'GET',
        headers: headers,
    }).then(data => {
        if (data.status !== 200) {
            res.status(404).send({
                msg: 'No GitHub profile found'
            });
        } else {
            return data.json().then(result => {
                res.json(result);
            });
        }
    }).catch(err => {
        console.error(err.message);
        res.status(500).send('Server Error');
    });
})
© www.soinside.com 2019 - 2024. All rights reserved.