2013-10-29 2 views
2

다음 코드는 내가 기대하는 것 이외의 일부 동작을 표시합니다.Node.js - 내가 기대하는대로 왜 이러한 모듈이 작동하지 않습니까?


내가 무엇을 기대 :

GET / -> 디스플레이 "에 오신 것을 환영합니다"하고 연결을 닫습니다

POST /pages -> 증가/카운터를 로그; POST 함수에 "표시하고 연결을 닫습니다.

GET /someRandomPath -> 카운터를 증가/기록하십시오. > 디스플레이 "에 오신 것을 환영합니다"하고 연결을 닫습니다

POST /pages - -

GET />카운터의 NO 증가/로그; 디스플레이 (404) 메시지


내가 관찰 무엇 "POST 함수에"표시하고 연결을 닫습니다.

GET /someRandomPath -> 카운터를 증가/기록하십시오. 디스플레이 (404) 메시지


코드 :

var express = require('express'); 
var request_counter = 0; 

var app = express() 

    .use(express.basicAuth('test', 'test')) 

    //serve the root (welcome) 
    .get('/', function(req, resp, next) { 
     resp.end('welcome'); 
    }) 

    // count/log the requests 
    .use(function(req, resp, next) { 
     console.log('request# ' + (++request_counter)); 
     next(); 
    }) 

    // serve "/pages" 
    .post('/pages', function (req, resp, next) { 
     console.log('in the POST function'); 
     resp.end('in the POST function'); 
    }) 

    // serve 404 
    .use(function (req, resp) { 
     resp 
      .status(404) 
      .end('BB: not found') 
     ; 
    }) 
; 

module.exports = app; 

왜 카운터가 나는 POST /pages를 호출 할 때 로그인/증가하지 않는 이유는 무엇입니까?

제가 주목하는 한 가지는 내가 //serve the root 섹션을 주석 처리하면 예상 한 동작을 얻게된다는 것입니다.

답변

1

this answer에 표시된대로 중간 정의 앞에 앞에 경로 정의를 시작한 것처럼 보입니다.

app.use(app.router)을 명시 적으로 사용하지 않지만 you use app.get 일 때 자동으로 호출됩니다.

이 알고, 내가 가장 가능성이 비슷한에 코드를 변경합니다 :

var express = require('express'); 
var request_counter = 0; 

var app = express() 

app.use(express.basicAuth('test', 'test')) 

// count/log the requests for all except '/' 
app.use(function(req, resp, next) { 

    if (req.path != '/') { 
     console.log('request# ' + (++request_counter)); 
    } 

    next(); 
}) 

//serve the root (welcome) 
app.get('/', function(req, resp, next) { 
    resp.end('welcome'); 
}) 

// serve "/pages" 
app.post('/pages', function (req, resp, next) { 
    console.log('in the POST function'); 
    resp.end('in the POST function'); 
}) 

// serve 404 for all the rest 
app.all('*', (function (req, resp) { 
    resp 
     .status(404) 
     .end('BB: not found') 
    ; 
})) 

app.listen(1234); 
+0

아, 그건 의미가 있습니다! 그냥 "미들웨어"라고 할 때, use()와 같은 Connect 물건을 의미합니까? 그리고 get()과 post() 같은 익스프레스 물건은 "비 미들웨어"입니까 ?? – loneboat

+0

@ loneboat - 예; [middlewhere] (http://expressjs.com/api.html#app.use)는 일반적으로 [app routes] (http://expressjs.com/api.html#app.VERB)가 실행되는 동안 'app.use'를 사용합니다. (non-middlewhere)는'app.get','app.post'와'app.all'을 사용합니다. – FriendlyGuy

관련 문제