[英]Axios error status code UnhandledPromiseRejectionWarning
[英]UnhandledPromiseRejectionWarning error using axios
我正在制作一個“UnhandledPromiseRejectionWarning:未處理的承諾拒絕”。 不允許我執行上述簡單請求的錯誤:
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))
})
});
我無法理解為什么會發生這種情況,因為我正在使用“.catch()”方法正確處理錯誤。 如何正確執行此請求?
在nodejs中本機不存在alert,因此錯誤可能來自.catch
嘗試使用此代碼:
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)
})
如果你想要更“現代”的方式
// 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
是一個宿主方法,可以在瀏覽器環境中找到,因此在node.js中不存在。
.then
拋出錯誤 catch
, catch
, catch
它由全局承諾拒絕處理程序處理。 要嘗試處理這種情況,請分別使用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.