关于res.redirect()的UnhandledPromiseRejectionWarning

时间:2019-07-15 11:03:16

标签: javascript node.js firebase google-cloud-firestore

我正在通过客户端在http://localhost:5000/myuniquecode之类的地址栏中通过get请求发送代码,然后在我的两个firestore数据库集合中检查此代码是否存在。对于授权用户,一个是nonauth_url,第二个是auth_url

如果找到匹配项,则将客户端重定向到该保存的URL,否则将其重定向到404.html页面。

nonauth_url的架构:

{
   code: 'nrgr89ehr8',  // a for nonauth_urls
   expiredAt: Date.now()+600000,
   url: 'http://www.example.com'
}

auth_url的架构:

{
    url1: {
       code: 'ag8rggur',
       redirectUrl: 'http://www.example.com'
    },
   url2: {
       code: 'ag8rggur',
       redirectUrl: 'http://www.example2.com'
    },
    .
    .
    .
    upto url5
}

我尝试返回这些重定向,但仍然会给出此警告。

任何人都可以通过重定向到所需的网址来解释为什么会发生警告,但代码仍在运行。

这是我来自客户端的获取请求的index.js代码。

必须修复警告,因为这会导致意外终止node.js。

app.get('/:code', (req, res) => {
   let url_code = req.params.code;
   let realcode = url_code.substring(1, url_code.length);
   if (urlId.isValid(realcode)) {
      if(url_code[0] == 'n') {
         db.collection('nonauth_url').where('code', '==', url_code).get().then((snapshot) => {
            if(snapshot.size > 0) {
               snapshot.forEach( doc => {
                  let data = doc.data();
                  if (data.expiredAt < Date.now()) {
                     res.redirect(data.url);
                  }
                  else {
                     res.status(404).redirect('404.html');                     
                  }
               }) ;
            } else {
               res.status(404).redirect('404.html');
            }
         }).catch( err => {
            res.status(500).redirect('404.html');
         }) ;
      } else if( url_code[0] == 'a') {
         db.collection('auth_url').get().then( snapshot => {
            if(snapshot.size > 0) {
               let flag = 0;
               snapshot.forEach( doc => {
                  let obj = doc.data();
                  let objArray = [];
                  for( key in obj) {
                     objArray.push(Object.assign(obj[key], {name: key}));
                  }
                  objArray.forEach((newObj) => {
                     if (newObj.code == url_code) {
                        res.redirect(newObj.redirectUrl);
                     } else {
                        flag = 1;
                     }
                  }) ;
               }) ;
               if (flag == 1) {
                  res.status(404).redirect('404.html');
               }
            } else {
               res.status(404).redirect('404.html');
            }
         }) ;
      } else{ // code doen't have 'a' or 'n' at starting
         res.status(404).redirect('404.html');
      }
   } else {
      res.status(404).redirect('404.html');
   }
}) ;

0 个答案:

没有答案