Browse Source

Fix: Server dumped the message "Error: Can't set headers after they are sent." when redirecting to moved page

Yuki Takei 8 years ago
parent
commit
99636727ad
2 changed files with 29 additions and 11 deletions
  1. 1 0
      config/env.dev.js
  2. 28 11
      lib/routes/page.js

+ 1 - 0
config/env.dev.js

@@ -11,6 +11,7 @@ module.exports = {
   DEBUG: [
     // 'express:*',
     // 'crowi:*',
+    // 'crowi:routes:page',
     // 'crowi:plugins:*',
     // 'crowi:InterceptorManager',
   ].join(),

+ 28 - 11
lib/routes/page.js

@@ -234,10 +234,15 @@ module.exports = function(crowi, app) {
 
     var pageTeamplate = 'customlayout-selector/page';
 
+    var isRedirect = false;
     Page.findPage(path, req.user, req.query.revision)
     .then(function(page) {
+      debug('Page found', page._id, page.path);
+
       // redirect
       if (page.redirectTo) {
+        debug(`Redirect to '${page.redirectTo}'`);
+        isRedirect = true;
         return res.redirect(encodeURI(page.redirectTo + '?redirectFrom=' + page.path));
       }
 
@@ -288,12 +293,17 @@ module.exports = function(crowi, app) {
       } else {
         return Promise.resolve();
       }
-    }).catch(function(err) {
-      // page not exists
+    })
+    // page not exists
+    .catch(function(err) {
+      debug('Page not found', page.path);
       // change template
       pageTeamplate = 'customlayout-selector/not_found';
-    }).then(function() {
-      return Page.findListByStartWith(path, req.user, queryOptions)
+    })
+    // get list pages
+    .then(function() {
+      if (!isRedirect) {
+        Page.findListByStartWith(path, req.user, queryOptions)
         .then(function(pageList) {
           if (pageList.length > limit) {
             pageList.pop();
@@ -308,14 +318,21 @@ module.exports = function(crowi, app) {
           renderVars.pages = pageList;
 
           return Promise.resolve();
+        })
+        .then(function() {
+          debug(`then 3: ${path}`);
+          return interceptorManager.process('beforeRenderPage', req, res, renderVars);
+        })
+        .then(function() {
+          debug(`then 4: ${path}`);
+          res.render(req.query.presentation ? 'page_presentation' : pageTeamplate, renderVars);
+        })
+        .catch(function(err) {
+          debug(`then 5: ${path}`);
+          console.log(err);
+          debug('Error on rendering pageListShowForCrowiPlus', err);
         });
-    }).then(function() {
-      return interceptorManager.process('beforeRenderPage', req, res, renderVars);
-    }).then(function() {
-      res.render(req.query.presentation ? 'page_presentation' : pageTeamplate, renderVars);
-    }).catch(function(err) {
-      console.log(err);
-      debug('Error on rendering pageListShowForCrowiPlus', err);
+      }
     });
   }