Reputation: 454
I want to get the list of the repositories by providing a username. Below is what I have done so far.
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');
}
})
(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)
Can anybody tell me how to resolve this error? I have looked at many resources but could not find any concrete.
Upvotes: 4
Views: 2402
Reputation: 664971
The problem is the return res.status(404).send(…)
in the first then
callback. The second then
callback will then try to res.json(result)
that return value.
You should instead write
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');
});
})
Upvotes: 4