首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >hapi.js -成功认证后如何重定向到最初请求的路由?

hapi.js -成功认证后如何重定向到最初请求的路由?
EN

Stack Overflow用户
提问于 2015-08-08 03:45:57
回答 1查看 3.9K关注 0票数 2

在hapi.js中有类似于hapi.js的东西吗?我试图将用户重定向回他们成功登录之前请求的原始页面。

EN

回答 1

Stack Overflow用户

发布于 2015-08-08 10:33:36

在使用hapi-auth-cookie方案时,有一个非常方便的设置。看看 in the options

当您将其设置为true时,重定向到您的登录页面将包含一个查询参数nextnext将是,等于原始请求的请求路径。

然后,您可以在成功登录时使用它重定向到所需的页面。下面是一个可以运行的示例,您可以使用该示例并根据需要进行修改:

代码语言:javascript
复制
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!');
});

为了检验这一点:

  • 在浏览器中导航到http://localhost:8080/greetings
  • 你将被重定向到/login
  • 单击登录按钮
  • 形成帖子到/login,然后在成功后重定向到/greetings
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31889428

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档