【问题标题】:UnhandledPromiseRejectionWarning error using axios使用 axios 的 UnhandledPromiseRejectionWarning 错误
【发布时间】:2018-07-31 09:59:53
【问题描述】:

我收到 “UnhandledPromiseRejectionWarning: Unhandled Promise Rejection.” 错误,我无法执行上述简单请求:

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()”方法正确处理错误。如何正确执行此请求?

【问题讨论】:

    标签: javascript node.js http axios


    【解决方案1】:

    alert是一个host方法,可以在浏览器环境中找到,因此在node.js中是不存在的。

    1. 它首先在.then 中抛出错误
    2. catch抓到,
    3. 现在在catch 内再次被抛出,
    4. 因为没有什么可以捕捉到最后一个 catch 它由全局承诺拒绝处理程序处理。

    要尝试处理这种情况,请分别使用 console.logconsole.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)
        })

    【讨论】:

      【解决方案2】:

      alert 在 nodejs 中本机不存在,因此错误可能来自.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)
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2019-12-13
        • 2018-02-23
        • 2021-11-17
        • 1970-01-01
        • 2019-03-24
        • 1970-01-01
        • 2019-11-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多