webpack-dev-server无法使用hapi和hapi-auth-cookie正确代理重定向到后端

时间:2016-07-24 09:46:16

标签: authentication cookies proxy webpack hapijs

当我启动hapi-server以及webpack-dev-server并转到localhost时:3000 / api / login显示502坏网关,页面上没有任何内容!感谢每一个帮助的人

这是我的webpack文件:

module.exports = {
    entry: ["./index.js"],
    output: {
        filename: "bundle.js"
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                    presets: ['react', 'es2015']
                }
            }
        ]
    },
    resolve: {
        extensions: ['', '.js', '.jsx']
    },
    devServer: {
        historyApiFallback: {
            index: 'index.html'
        },
        stats: 'normal',
        host: process.env.HOST || 'localhost',
        port: process.env.PORT || 3000,
        proxy: {
            '/api/*': {
                target: 'http//localhost:9000',
                secure: false
            }
        }
    }
};

这是我的hapi-server:

const Hapi = require('hapi');
const Inert = require('inert');
const config = require('./config');
const CookieAuth = require('hapi-auth-cookie');

const server = new Hapi.Server();
server.connection({port: 9000});

const options = {
    ops: {
        interval: config.hapiGoodInterval
    },
    reporters: {
        console: [{
            module: 'good-squeeze',
            name: 'Squeeze',
            args: [{ log: '*', response: '*' }]
        }, {
            module: 'good-console'
        }, 'stdout'],
        file: [{
            module: 'good-squeeze',
            name: 'Squeeze',
            args: [{ ops: '*' }]
        }, {
            module: 'good-squeeze',
            name: 'SafeJson'
        }, {
            module: 'good-file',
            args: ['./logs/fixtures/file_log']
        }]
    }
};
server.register(CookieAuth, (err) => {
    if (err) {
        throw err;
    }
});

server.register(Inert, ()=>{});
server.register({
    register: require('good'),
    options,
}, (err) => {
    if (err) {
        return console.error(err);
    }
    server.start(() => {
        console.info(`Server started at ${ server.info.uri }`);
    });
});

const cache = server.cache({ segment: 'sessions', expiresIn: 3 * 24 * 60 * 60 * 1000 });
server.app.cache = cache;

server.auth.strategy('session', 'cookie', true, {
    password: 'Vaj57zED9nsYeMJGP2hnfaxU874t6DV5',
    cookie: 'sid-example',
    redirectTo: '/api/login',
    isSecure: false,
    validateFunc: function (request, session, callback) {

        cache.get(session.sid, (err, cached) => {

            if (err) {
                return callback(err, false);
            }

            if (!cached) {
                return callback(null, false);
            }

            return callback(null, true, cached.account);
        });
    }
});

server.route(require('./routes'));

以下是路线:

var Handlers = require('./handlers');
var Joi = require('joi');
var Routes = [
  {
      path: '/api/hello',
      method: 'GET',
      config: {
          auth:false,
          handler: function (request, reply) {
              reply('Hello from the server')
          }
      }
  },
  {
    method: ['GET', 'POST'],
    path: '/api/login',
    config: {
        handler: Handlers.login,
        auth: { mode: 'try' },
        plugins: {
          'hapi-auth-cookie': { redirectTo: false }
        }
    }
  },
  {
    path: '/api/logout',
    method: 'GET',
    handler: Handlers.logout
  }
];

最后是处理程序:

const r = require('rethinkdb');
var {Post, User, Opinion} = require('./rethinkdb/models/all');

class Handlers {

    static login(request, reply) {
        let username = 'pesho';
        let password = '12345';

        let uuid = 1;

        if (request.auth.isAuthenticated) {
            return reply.redirect('/');
        }

        let message = '';
        let account = null;

        if (request.method === 'post') {

            if (!request.payload.username ||
                !request.payload.password) {

                message = 'Missing username or password';
            }
            else {
                if (password !== request.payload.password || username !== request.payload.username) {
                    message = 'Invalid username or password';
                }
            }
        }

        if (request.method === 'get' || message) {

            return reply('<html><head><title>Login page</title></head><body>' +
                (message ? '<h3>' + message + '</h3><br/>' : '') +
                '<form method="post" action="/api/login">' +
                'Username: <input type="text" name="username"><br>' +
                'Password: <input type="password" name="password"><br/>' +
                '<input type="submit" value="Login"></form></body></html>');

        }

        const sid = String(++uuid);
        request.server.app.cache.set(sid, { account: account }, 0, (err) => {

            if (err) {
                reply(err);
            }

            request.cookieAuth.set({ sid: sid });
            return reply.redirect('/');
        });
    }

    static logout(request, reply) {
        request.cookieAuth.clear();
        return reply.redirect('/');
    };
}

module.exports = Handlers;

1 个答案:

答案 0 :(得分:0)

问题很简单 - 转储,但它是: 您必须在代理目标

的末尾添加“/”
       proxy: {
            '/api/*': {
                target: 'http://localhost:9000/',<= This here
                secure: false
            }
        },