1

I am trying to fetch web pages using express static and below is the server code.

app.use(express.static('DIR/webfiles'));
app.get('/test', function(req, res) {
    console.log("got req");
    res.sendfile("login.html");
});

app.get('/', function(req, res) {
    console.log("got req");
    res.sendfile("login.html");
});

when I request for localhost:port/test (from browser), I am able to see login.html page and it prints "got req" on server end but when I request for localhost:port or localhost:port/ , I am getting some other file in webfiles folder. It does not print "got req". Is empty GET handler overridden by express static?

When I remove "app.use(express.static('DIR/webfiles'));" line, it is able to get empty GET request but doesn't work in way I want it to. Why it is not getting empty request and how to handle empty requests.

3
  • As far as i know localhost:port request automatically adds / to your request by default, which then becomes localhost:port/. So practically speaking you should get login page and not some other file. Commented Dec 18, 2015 at 12:00
  • localhost:port/ also gives same result Commented Dec 18, 2015 at 12:01
  • Try using the node core module path = require ('path') then use the __dirname and path.join() on your directory. That will ensure you hit your static target directory. Commented Dec 18, 2015 at 12:14

1 Answer 1

1

Express will process the various route handlers (including the static middleware) in order of declaration.

If you request /, the static middleware will check for a file called webfiles/index.html, and if it exists, it will be returned.

To override this behaviour, make sure that you declare your own route handler before the static middleware declaration:

// This will match requests to `/` and since it's declared before
// the static middleware, it will get to handle those requests.
app.get('/', function(req, res) {
  console.log("got req");
  res.sendfile("login.html");
});

app.use(express.static('DIR/webfiles'));
Sign up to request clarification or add additional context in comments.

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.