0

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.

2 Answers 2

1

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')));
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Robert, yes, I have index.html into public folder. You totally understand the problem and I solved it declaring the get before static middleware, but with a little edit, using next() instead res.end(). Thank you !
0

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')));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.