2015-08-08 31 views

回答

5

當使用hapi-auth-cookie方案時,有一個方便的設置用於此確切目的。看看appendNext in the options

當您將其設置爲true時,重定向到您的登錄頁面將包含查詢參數nextnext將爲等於原始請求的請求路徑。

然後,您可以在成功登錄時使用此選項重定向到所需的頁面。這裏有一個可運行的例子,你可以玩,並修改您的需要:在瀏覽器中

  • 導航到http://localhost:8080/greetings
  • 你會被重定向到/login
  • var Hapi = require('hapi'); 
    
    var server = new Hapi.Server(); 
    server.connection({ port: 8080 }); 
    
    server.register(require('hapi-auth-cookie'), function (err) { 
    
        server.auth.strategy('session', 'cookie', { 
         password: 'secret', 
         cookie: 'sid-example', 
         redirectTo: '/login', 
         appendNext: true,  // adds a `next` query value 
         isSecure: false 
        }); 
    }); 
    
    server.route([ 
        { 
         method: 'GET', 
         path: '/greetings', 
         config: { 
          auth: 'session', 
          handler: function (request, reply) { 
    
           reply('Hello there ' + request.auth.credentials.name); 
          } 
         } 
        }, 
        { 
         method: ['GET', 'POST'], 
         path: '/login', 
         config: { 
          handler: function (request, reply) { 
    
           if (request.method === 'post') { 
            request.auth.session.set({ 
             name: 'John Doe' // for example just let anyone authenticate 
            }); 
    
            return reply.redirect(request.query.next); // perform redirect 
           } 
    
           reply('<html><head><title>Login page</title></head><body>' + 
             '<form method="post"><input type="submit" value="login" /></form>' + 
             '</body></html>'); 
          }, 
          auth: { 
           mode: 'try', 
           strategy: 'session' 
          }, 
          plugins: { 
           'hapi-auth-cookie': { 
            redirectTo: false 
           } 
          } 
         } 
        } 
    ]); 
    
    server.start(function (err) { 
    
        if (err) { 
         throw err; 
        } 
    
        console.log('Server started!'); 
    }); 
    

    爲了驗證這一點,

  • 點擊登錄按鈕
  • 將帖子發送到/login,然後重定向到/greetings成功
相關問題