The following code displays some behavior other than what I am expecting.


What I expect:

GET / --> display "Welcome" and close the connection

POST /pages --> increment/log the counter; display "in the POST function", and close the connection

GET /someRandomPath --> increment/log the counter; display 404 message


What I observe:

GET / --> display "Welcome" and close the connection

POST /pages --> NO increment/log of the counter; display "in the POST function", and close the connection

GET /someRandomPath --> increment/log the counter; display 404 message


Code:

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;

Why does the counter not increment/log when I call POST /pages ?

One thing I notice is that if I comment out the //serve the root section, I get the behavior I expect.

有帮助吗?

解决方案

It looks as if you're supposed to define all of your middlewhere before you start defining routes, as noted in this answer.

You're not explicitly using app.use(app.router), but it's automatically called when you use app.get.

Knowing this, I would most likely change your code to something similar to this:

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top