I'm geting an "UnhandledPromiseRejectionWarning: Unhandled promise rejection." error that doesn't allow me to perform this simple request above:
app.get('/', function (req, res) {
const GITHUB_AUTH_ACCESSTOKEN_URL = 'https://github.com/login/oauth/access_token'
const CLIENT_ID = '123'
const CLIENT_SECRET = '456'
axios({
method: 'post',
url: GITHUB_AUTH_ACCESSTOKEN_URL,
data: {
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET
}
})
.then(function (response) {
alert('Sucess ' + JSON.stringify(response))
})
.catch(function (error) {
alert('Error ' + JSON.stringify(error))
})
});
I can't understand why this is happening because I'm properly handling the error with the ".catch()" method. How can I perform this request correctly?
alert doesn't exists natively in nodejs, so the error is probably coming from the .catch
try instead this code:
axios({
method: 'post',
url: GITHUB_AUTH_ACCESSTOKEN_URL,
data: {
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET
}
})
.then(function ({data}) {
console.log('Success ' + JSON.stringify(data))
})
.catch(function (error) {
console.log('Error ' + error.message)
})
if you want bit more "modern" way
// notice the async () =>
app.get('/', async (req, res) => {
const GITHUB_AUTH_ACCESSTOKEN_URL = 'https://github.com/login/oauth/access_token'
const CLIENT_ID = '123'
const CLIENT_SECRET = '456'
try {
const { data } = await axios({
method: 'post',
url: GITHUB_AUTH_ACCESSTOKEN_URL,
data: {
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET
}
})
console.log(data)
} catch (err) {
console.error(err.message)
}
});
alert is a host method, which can be found in browser environment, thus it doesn't exist in node.js.
.then catch, catch, catch it's handled by global promise rejection handler.To try to handle the situation start with changing every alert with console.log and console.error respectively:
axios({
method: 'post',
url: GITHUB_AUTH_ACCESSTOKEN_URL,
data: {
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET
}
})
.then(function (response) {
console.log('Success ' + JSON.stringify(response))
})
.catch(function (error) {
console.error('Error ' + error.message)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With