Andrea D'Ubaldo
Andrea D'Ubaldo

Reputation: 137

Can't parse GET request using express

I read a lot about node, express and many useful modules. I'm trying to parse GET HTTP request but I'm doing something wrong.

Maybe this problem could be solved using express.Router() and views engine but I would like to know WHY this code doesn't work?

Server is up and running! Public files are very well served BUT I cannot parse GET request.

app.use(express.static(path.join(__dirname, 'public')));

/*I would like to get req.session here*/
app.get('/', function (req, res, next) {
    console.log('I'm trying to log this string');
})

I'm also using morgan to log all HTTP request and this is the output:

Listening at: http://localhost:8080
GET / 200 14.288 ms - 9139
GET /css/materialize.css 304 16.311 ms - -
GET /css/style.css 304 24.775 ms - -
GET /js/materialize.js 304 21.287 ms - -
GET /js/init.js 304 20.238 ms - -
GET /js/index.js 200 51.159 ms - 2719
GET /fonts/roboto/Roboto-Regular.woff2 304 2.419 ms - -
GET /fonts/roboto/Roboto-Medium.woff2 304 3.663 ms - -
GET /fonts/roboto/Roboto-Light.woff2 304 7.958 ms - -
GET /fonts/roboto/Roboto-Bold.woff2 304 9.010 ms - -

It works commenting :

//app.use(express.static(path.join(__dirname, 'public')));

But, obviously, no file are served.

Thank you!

PS: I never seen tutorial or code snippet explaining the situation described above.

Upvotes: 0

Views: 197

Answers (2)

Andrea D'Ubaldo
Andrea D'Ubaldo

Reputation: 137

Thanks to @robertklep, I solved doing this :

app.get('/', function (req, res, next) {
  console.log('I'm trying to log this string');
  // make sure to end the response, to prevent hanging requests.
  next();
});

app.use(express.static(path.join(__dirname, 'public')));

Upvotes: 0

robertklep
robertklep

Reputation: 203231

I'm guessing that you have a file called index.html in the public/ directory, which is the one that will get served when requesting /, because that's what express.static() does by default.

You can disable that behaviour, so the request will be passed to your / handler:

app.use(express.static(path.join(__dirname, 'public'), { index : false }));

This is documented here.

Alternatively, you can make sure that the request hits the / handler by declaring it before the static middleware:

app.get('/', function (req, res, next) {
  console.log('I'm trying to log this string');
  // make sure to end the response, to prevent hanging requests.
  res.end();
});

app.use(express.static(path.join(__dirname, 'public')));

Upvotes: 1

Related Questions