如果用户未登录,node.js表示中间件重定向

时间:2015-03-19 11:58:02

标签: node.js express response middleware

如果用户尝试导航到http://www.example.com/news.html(或任何其他非登录页面的html页面),如果用户未登录,我需要将他重定向到登录页面。

我尝试了下面的代码,但是一旦我进入if的真正代码块,res.render或res.redirect就完全没有了。如果我在console.log那里它正常工作。所以我猜res对象有问题。

app.use(function(req, res, next) {
    if (req.session.user == undefined) {
        // if user is not logged-in redirect back to login page //
        res.render('es/login', {
            title: 'Hello - Please Login To Your Account'
        });
    } else {
        next();
    }
});

如果我是console.log(res),我得到:

    { domain: null,
  _events: { finish: [Function], header: [Function] },
  _maxListeners: 10,
  output: [],
  outputEncodings: [],
  writable: true,
  _last: false,
  chunkedEncoding: false,
  shouldKeepAlive: true,
  useChunkedEncodingByDefault: true,
  sendDate: true,
  _headerSent: false,
  _header: '',
  _hasBody: true,
  _trailer: '',
  finished: false,
  _hangupClose: false,
  socket: 
   { _connecting: false,
     _handle: 
      { fd: 24,
        writeQueueSize: 0,
        owner: [Circular],
        onread: [Function: onread],
        reading: true },
     _readableState: 
      { highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: false,
        ended: false,
        endEmitted: false,
        reading: true,
        calledRead: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        objectMode: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: true,
     domain: null,
     _events: 
      { end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        drain: [Object],
        timeout: [Function],
        error: [Function],
        close: [Object] },
     _maxListeners: 10,
     _writableState: 
      { highWaterMark: 16384,
        objectMode: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        buffer: [],
        errorEmitted: false },
     writable: true,
     allowHalfOpen: true,
     onend: [Function],
     destroyed: false,
     bytesRead: 3233,
     _bytesDispatched: 306029,
     _pendingData: null,
     _pendingEncoding: '',
     server: 
      { domain: null,
        _events: [Object],
        _maxListeners: 10,
        _connections: 6,
        connections: [Getter/Setter],
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        allowHalfOpen: true,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _connectionKey: '4:0.0.0.0:3000' },
     _idleTimeout: 120000,
     _idleNext: 
      { _connecting: false,
        _handle: [Object],
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        onend: [Function],
        destroyed: false,
        bytesRead: 2662,
        _bytesDispatched: 272567,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Circular],
        _idleStart: 1426765947031,
        _monotonicStartTime: 121119709,
        parser: [Object],
        ondata: [Function],
        _paused: false,
        _httpMessage: null },
     _idlePrev: { _idleNext: [Circular], _idlePrev: [Object] },
     _idleStart: 1426765947035,
     _monotonicStartTime: 121119713,
     parser: 
      { _headers: [],
        _url: '',
        onHeaders: [Function: parserOnHeaders],
        onHeadersComplete: [Function: parserOnHeadersComplete],
        onBody: [Function: parserOnBody],
        onMessageComplete: [Function: parserOnMessageComplete],
        socket: [Circular],
        incoming: [Object],
        maxHeaderPairs: 2000,
        onIncoming: [Function] },
     ondata: [Function],
     _paused: false,
     _httpMessage: [Circular] },
  connection: 
   { _connecting: false,
     _handle: 
      { fd: 24,
        writeQueueSize: 0,
        owner: [Circular],
        onread: [Function: onread],
        reading: true },
     _readableState: 
      { highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: false,
        ended: false,
        endEmitted: false,
        reading: true,
        calledRead: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        objectMode: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: true,
     domain: null,
     _events: 
      { end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        drain: [Object],
        timeout: [Function],
        error: [Function],
        close: [Object] },
     _maxListeners: 10,
     _writableState: 
      { highWaterMark: 16384,
        objectMode: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        buffer: [],
        errorEmitted: false },
     writable: true,
     allowHalfOpen: true,
     onend: [Function],
     destroyed: false,
     bytesRead: 3233,
     _bytesDispatched: 306029,
     _pendingData: null,
     _pendingEncoding: '',
     server: 
      { domain: null,
        _events: [Object],
        _maxListeners: 10,
        _connections: 6,
        connections: [Getter/Setter],
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        allowHalfOpen: true,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _connectionKey: '4:0.0.0.0:3000' },
     _idleTimeout: 120000,
     _idleNext: 
      { _connecting: false,
        _handle: [Object],
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        onend: [Function],
        destroyed: false,
        bytesRead: 2662,
        _bytesDispatched: 272567,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Circular],
        _idleStart: 1426765947031,
        _monotonicStartTime: 121119709,
        parser: [Object],
        ondata: [Function],
        _paused: false,
        _httpMessage: null },
     _idlePrev: { _idleNext: [Circular], _idlePrev: [Object] },
     _idleStart: 1426765947035,
     _monotonicStartTime: 121119713,
     parser: 
      { _headers: [],
        _url: '',
        onHeaders: [Function: parserOnHeaders],
        onHeadersComplete: [Function: parserOnHeadersComplete],
        onBody: [Function: parserOnBody],
        onMessageComplete: [Function: parserOnMessageComplete],
        socket: [Circular],
        incoming: [Object],
        maxHeaderPairs: 2000,
        onIncoming: [Function] },
     ondata: [Function],
     _paused: false,
     _httpMessage: [Circular] },
  app: 
   { [Function: app]
     use: [Function],
     handle: [Function],
     listen: [Function],
     setMaxListeners: [Function: setMaxListeners],
     emit: [Function: emit],
     addListener: [Function: addListener],
     on: [Function: addListener],
     once: [Function: once],
     removeListener: [Function: removeListener],
     removeAllListeners: [Function: removeAllListeners],
     listeners: [Function: listeners],
     route: '/',
     stack: 
      [ [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object] ],
     init: [Function],
     defaultConfiguration: [Function],
     engine: [Function],
     param: [Function],
     set: [Function],
     path: [Function],
     enabled: [Function],
     disabled: [Function],
     enable: [Function],
     disable: [Function],
     configure: [Function],
     get: [Function],
     post: [Function],
     put: [Function],
     head: [Function],
     delete: [Function],
     options: [Function],
     trace: [Function],
     copy: [Function],
     lock: [Function],
     mkcol: [Function],
     move: [Function],
     propfind: [Function],
     proppatch: [Function],
     unlock: [Function],
     report: [Function],
     mkactivity: [Function],
     checkout: [Function],
     merge: [Function],
     'm-search': [Function],
     notify: [Function],
     subscribe: [Function],
     unsubscribe: [Function],
     patch: [Function],
     all: [Function],
     del: [Function],
     render: [Function],
     request: {},
     response: {},
     cache: {},
     settings: 
      { 'x-powered-by': true,
        env: 'development',
        views: '/Users/jaitor/Documents/f1racing/app/server/views',
        'jsonp callback name': 'callback',
        'json spaces': 2,
        port: 3000,
        'view engine': 'jade' },
     engines: {},
     viewCallbacks: [],
     _events: { mount: [Function] },
     _router: 
      { map: [Object],
        params: {},
        _params: [],
        caseSensitive: false,
        strict: false,
        middleware: [Function: router] },
     routes: { get: [Object], post: [Object] },
     router: [Getter],
     locals: { [Function: locals] settings: [Object], pretty: true },
     _usedRouter: true },
  _headers: { 'x-powered-by': 'Express' },
  _headerNames: { 'x-powered-by': 'X-Powered-By' },
  req: 
   { _readableState: 
      { highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: false,
        ended: true,
        endEmitted: true,
        reading: false,
        calledRead: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        objectMode: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: false,
     domain: null,
     _events: { data: [Object], readable: [Function], end: [Object] },
     _maxListeners: 10,
     socket: 
      { _connecting: false,
        _handle: [Object],
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        onend: [Function],
        destroyed: false,
        bytesRead: 3233,
        _bytesDispatched: 306029,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 1426765947035,
        _monotonicStartTime: 121119713,
        parser: [Object],
        ondata: [Function],
        _paused: false,
        _httpMessage: [Circular] },
     connection: 
      { _connecting: false,
        _handle: [Object],
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        onend: [Function],
        destroyed: false,
        bytesRead: 3233,
        _bytesDispatched: 306029,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 1426765947035,
        _monotonicStartTime: 121119713,
        parser: [Object],
        ondata: [Function],
        _paused: false,
        _httpMessage: [Circular] },
     httpVersion: '1.1',
     complete: true,
     headers: 
      { host: 'localhost:3000',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:36.0) Gecko/20100101 Firefox/36.0',
        accept: '*/*',
        'accept-language': 'es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3',
        'accept-encoding': 'gzip, deflate',
        'x-requested-with': 'XMLHttpRequest',
        referer: 'http://localhost:3000/es/myteam.html?community=54e07946e4b0dff6d40bde1c',
        cookie: 's_fid=79F1544C1E84B837-2BDACE625059FB4C; s_lv=1422809809979; connect.sid=s%3AFVYUZZh5S6Qj1qV8Zu964p9z.gwbNG3tC0qzr8llFHlpaUjURED%2Bm26lGZ3vYYu%2BloOM',
        connection: 'keep-alive' },
     trailers: {},
     _pendings: [],
     _pendingIndex: 0,
     url: '/getraces?community=54e07946e4b0dff6d40bde1c',
     method: 'GET',
     statusCode: null,
     client: 
      { _connecting: false,
        _handle: [Object],
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        onend: [Function],
        destroyed: false,
        bytesRead: 3233,
        _bytesDispatched: 306029,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 1426765947035,
        _monotonicStartTime: 121119713,
        parser: [Object],
        ondata: [Function],
        _paused: false,
        _httpMessage: [Circular] },
     _consuming: true,
     _dumped: false,
     httpVersionMajor: 1,
     httpVersionMinor: 1,
     upgrade: false,
     originalUrl: '/getraces?community=54e07946e4b0dff6d40bde1c',
     _parsedUrl: 
      { protocol: null,
        slashes: null,
        auth: null,
        host: null,
        port: null,
        hostname: null,
        hash: null,
        search: '?community=54e07946e4b0dff6d40bde1c',
        query: 'community=54e07946e4b0dff6d40bde1c',
        pathname: '/getraces',
        path: '/getraces?community=54e07946e4b0dff6d40bde1c',
        href: '/getraces?community=54e07946e4b0dff6d40bde1c' },
     query: { community: '54e07946e4b0dff6d40bde1c' },
     app: 
      { [Function: app]
        use: [Function],
        handle: [Function],
        listen: [Function],
        setMaxListeners: [Function: setMaxListeners],
        emit: [Function: emit],
        addListener: [Function: addListener],
        on: [Function: addListener],
        once: [Function: once],
        removeListener: [Function: removeListener],
        removeAllListeners: [Function: removeAllListeners],
        listeners: [Function: listeners],
        route: '/',
        stack: [Object],
        init: [Function],
        defaultConfiguration: [Function],
        engine: [Function],
        param: [Function],
        set: [Function],
        path: [Function],
        enabled: [Function],
        disabled: [Function],
        enable: [Function],
        disable: [Function],
        configure: [Function],
        get: [Function],
        post: [Function],
        put: [Function],
        head: [Function],
        delete: [Function],
        options: [Function],
        trace: [Function],
        copy: [Function],
        lock: [Function],
        mkcol: [Function],
        move: [Function],
        propfind: [Function],
        proppatch: [Function],
        unlock: [Function],
        report: [Function],
        mkactivity: [Function],
        checkout: [Function],
        merge: [Function],
        'm-search': [Function],
        notify: [Function],
        subscribe: [Function],
        unsubscribe: [Function],
        patch: [Function],
        all: [Function],
        del: [Function],
        render: [Function],
        request: {},
        response: {},
        cache: {},
        settings: [Object],
        engines: {},
        viewCallbacks: [],
        _events: [Object],
        _router: [Object],
        routes: [Object],
        router: [Getter],
        locals: [Object],
        _usedRouter: true },
     res: [Circular],
     next: [Function: next],
     body: {},
     files: {},
     secret: undefined,
     cookies: 
      { s_fid: '79F1544C1E84B837-2BDACE625059FB4C',
        s_lv: '1422809809979',
        'connect.sid': 's:FVYUZZh5S6Qj1qV8Zu964p9z.gwbNG3tC0qzr8llFHlpaUjURED+m26lGZ3vYYu+loOM' },
     signedCookies: {},
     sessionStore: { sessions: [Object], generate: [Function], _events: [Object] },
     sessionID: 'FVYUZZh5S6Qj1qV8Zu964p9z',
     pipe: [Function],
     addListener: [Function: addListener],
     on: [Function: addListener],
     pause: [Function],
     resume: [Function],
     read: [Function],
     session: { cookie: [Object] },
     originalMethod: 'GET',
     locale: 'es',
     rawLocale: 
      { code: 'es',
        language: 'es',
        normalized: 'es',
        score: 1,
        defaulted: false } },
  viewCallbacks: [],
  locals: [Function: locals],
  end: [Function] }
{ domain: null,
  _events: { finish: [Function], header: [Function] },
  _maxListeners: 10,
  output: [],
  outputEncodings: [],
  writable: true,
  _last: false,
  chunkedEncoding: false,
  shouldKeepAlive: true,
  useChunkedEncodingByDefault: true,
  sendDate: true,
  _headerSent: false,
  _header: '',
  _hasBody: true,
  _trailer: '',
  finished: false,
  _hangupClose: false,
  socket: 
   { _connecting: false,
     _handle: 
      { fd: 24,
        writeQueueSize: 0,
        owner: [Circular],
        onread: [Function: onread],
        reading: true },
     _readableState: 
      { highWaterMark: 16384,
        buffer: [],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: false,
        ended: false,
        endEmitted: false,
        reading: true,
        calledRead: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        objectMode: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: true,
     domain: null,
     _events: 
      { end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        drain: [Object],
        timeout: [Function],
        error: [Function],
        close: [Object] },
     _maxListeners: 10,
     _writableState: 
      { highWaterMark: 16384,
        objectMode: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        buffer: [],
        errorEmitted: false },
     writable: true,
     allowHalfOpen: true,
     onend: [Function],
     destroyed: false,
     bytesRead: 4333,
     _bytesDispatched: 312302,
     _pendingData: null,
     _pendingEncoding: '',
     server: 
      { domain: null,
        _events: [Object],
        _maxListeners: 10,
        _connections: 6,
        connections: [Getter/Setter],
        _handle: [Object],
        _usingSlaves: false,
        _slaves: [],
        allowHalfOpen: true,
        httpAllowHalfOpen: false,
        timeout: 120000,
        _connectionKey: '4:0.0.0.0:3000' },
     _idleTimeout: 120000,
     _idleNext: 
      { _connecting: false,
        _handle: [Object],
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        onend: [Function],
        destroyed: false,
        bytesRead: 3763,
        _bytesDispatched: 289060,
        _pendingData: null,
        _pendingEncoding: '',
        server: [Object],
        _idleTimeout: 120000,
        _idleNext: [Object],
        _idlePrev: [Circular],
        _idleStart: 1426765947154,
        _monotonicStartTime: 121119832,
        parser: [Object],
        ondata: [Function],
        _paused: false,
        _httpMessage: null },
     _idlePrev: { _idleNext: [Circular], _idlePrev: [Object] },
     _idleStart: 1426765947654,
     _monotonicStartTime: 121120332,
     parser: 
      { _headers: [],
        _url: '',
        onHeaders: [Function: parserOnHeaders],
        onHeadersComplete: [Function: parserOnHeadersComplete],
        onBody: [Function: parserOnBody],
        onMessageComplete: [Function: parserOnMessageComplete],
        socket: [Circular],
        incoming: [Object],
        maxHeaderPairs: 2000,
        onIncoming: [Function] },
     ondata: [Function],
     _paused: false,
     _httpMessage: [Circular] },
  connection: 
   { _connecting: false,
     _handle: 
      { fd: 24,
        writeQueueSize: 0,
        owner: [Circular],
        onread: [Function: onread],
        reading: true },
     _readableState: 
  ......... continues....}

我正在使用的Express版本:“3.4.4”

编辑14/07/2015。我的问题仍然存在,我正在编写更多代码,看看是否有人可以帮助我...

我的主要app.js代码:

var express = require('express');
var http = require('http');
var app = express();

app.configure(function(){
    app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/app/server/views');
    app.set('view engine', 'jade');
    app.locals.pretty = true;
//  app.use(express.favicon());
//  app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(express.session({ secret: 'Whateverpass',cookie:{maxAge:30 * 24 * 60*60*1000}}));
    app.use(express.methodOverride());
    app.use(require('stylus').middleware({ src: __dirname + '/app/public' }));
    app.use(express.static(__dirname + '/app/public'));
});

if ('development' == app.get('env')) {
}

app.configure('development', function(){
    app.use(express.errorHandler());
});

require('./app/server/router')(app);

var httpserver = http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

我的router.js位于('./app/server/router'):

var locale = require(“locale”); var supported = new locale.Locales([“en”,“es”]);

module.exports = function(app){

app.use(locale(supported));

app.use(function(req, res, next) {
    if (req.session.user == undefined) {
        // if user is not logged-in redirect back to login page //
        res.render('es/login', {
            title: 'Hello - Please Login To Your Account'
        });
    } else {
        next();
    }
});

app.get('/', function(req, res){
     [...]
});

app.post('/', function(req, res){
     [...]
});

[...]

}

2 个答案:

答案 0 :(得分:2)

尝试在returnres.render

之前使用res.redirect
app.use(function(req, res, next) {
    if (req.session.user == undefined) {  
          return res.render('es/login', { title: 'Hello - Please Login To Your Account' });
        }   
        else {
            next();
        }
    });

答案 1 :(得分:0)

尝试编写返回语句,如下所示:

return (
         res.render('es/login', {
            title: 'Hello - Please Login To Your Account'
        });
);
相关问题