2017-12-08 1 views
0

노드 & Express와 함께 정말 이상한 문제가 발생했습니다. 이렇게 될 것인수 객체와 인수가 다릅니다.

app.get('/', auth, handler) 
app.get('/', auth('role'), handler) 
app.get('/', auth('role', 'scope'), handler) 

확실한 방법이 작업을 수행하는 :

는 나도 세 가지 방법으로 호출 할 수있는 미들웨어 기능을 가지고

exports.auth = (a, b, c) => { 

    let role, scope; 

    switch(arguments.length) { 
     case 3: 
      // Called directly by express router 
      handleAuth(a, b, c); 
      break; 

     case 2: 
     case 1: 
      // Called with role/scope, return handler 
      // but don't execute 
      role = a; 
      scope = b; 
      return handleAuth; 
    } 


    function handleAuth(req, res, next) { 

     // Do some custom auth handling, can 
     // check here if role/scope is set 
     return next(); 

    } 
} 

을하지만, 난 arguments.length에 대해 아주 이상한 결과가 나타납니다. 두 번째 방법으로 호출 할 때는 arguments.length == 5이고 인수는 role이 아닙니다. 나는 함수 내에서 a, b, c를 기록 할 경우

[ '0': '[object Object]', 
    '1': 'function require(path) {\n try {\n  exports.requireDepth += 1;\n  return mod.require(path);\n } finally {\n  exports.requireDepth -= 1;\n }\n }', 
    '2': '[object Object]', 
    '3': '/Users/redacted/auth/index.js', 
    '4': '/Users/redacted/auth' ] 

, 나는 a: 'role', b: undefined, c: undefined를 얻을.

나는 Runkit에서 그것을 재현하려고 노력했지만 운이 없었어요 : https://runkit.com/benedictlewis/5a2a6538895ebe00124eb64e

답변

1

arguments은 화살표 기능 (() =>)에 노출되지 않습니다. 필요한 경우 대신 정규 함수를 사용하십시오.

exports.auth = function(a, b, c) { 

    let role, scope; 

    switch(arguments.length) { 
    ... 

사이드 노트 다음 arguments 당신의 그 화살표 기능이 실제로 각 모듈/필요한 코드를 실행하는 동안 Node.js를 사용하는 래퍼 함수에서 선택됩니다에서 참조하십시오. 이 함수를 사용하면 exports, require, module, __dirname__filename과 같은 "마법의"변수에 액세스 할 수 있으므로 5 인수가 표시됩니다.

0

내가 case가 고장이라고 생각합니다.

'use strict'; 
let express = require('express'); 
let app = express(); 

//app.get('/', auth, handler); 
app.get('/', auth('role'), handler); 
//app.get('/', auth('role', 'scope'), handler); 

function auth (a, b, c) { 
    let role; 
    if (a == 'role') { 
     role = 'user'; 
     return handleAuth; 
    } 

    if (a != 'role')   
     return handleAuth(a, b, c); 

    function handleAuth(req, res, next) { 
     console.log(role || 'guest'); 
     next(); 
    } 
} 

function handler (req, res, next) { 
    res.send('OK'); 
} 

app.listen(3000,() => console.log('Listening on port 3000')); 

P. 이 호,이 코드는 매듭이있다.