[英]UnhandledPromiseRejectionWarning error using axios
I'm geting an "UnhandledPromiseRejectionWarning: Unhandled promise rejection." 我正在制作一个“UnhandledPromiseRejectionWarning:未处理的承诺拒绝”。 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. 我无法理解为什么会发生这种情况,因为我正在使用“.catch()”方法正确处理错误。 How can I perform this request correctly?
如何正确执行此请求?
alert doesn't exists natively in nodejs, so the error is probably coming from the .catch
在nodejs中本机不存在alert,因此错误可能来自
.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. alert
是一个宿主方法,可以在浏览器环境中找到,因此在node.js中不存在。
.then
.then
抛出错误 catch
, catch
, catch
, catch
, catch
it's handled by global promise rejection handler. catch
它由全局承诺拒绝处理程序处理。 To try to handle the situation start with changing every alert with console.log
and console.error
respectively: 要尝试处理这种情况,请分别使用
console.log
和console.error
更改每个警报:
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) })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.