Code inside get not running after using express.static

KevinHu Source

This is my nodejs express setting:

var express = require('express');
var app = express();

app.use(express.static('public'));

app.get('*', function (req, res) {
  res.sendfile('public/index.html')
});

app.listen(process.env.PORT || 3000, function () {
  console.log('Example app listening on port 3000!');
});


module.exports = app;

I found out that when it use:

app.use(express.static('public'));

Nothing runs inside this get:

app.get('*', function (req, res) { // nothing runs here res.sendfile('public/index.html') });

ps: I want to redirect (http -> https) inside that get.

node.jshttpexpressserver

Answers

answered 2 years ago jfriend00 #1

If you want to redirect all http requests to https, then insert an app.use() middleware as the first request handler with the redirect logic to https. Express processes request handlers in the order you define them and you will want this middleware to be processed first before your express.static() middleware.

You will, of course, need to put all your other request handlers on an https server (not on the http server) so the htts server can process your URLs after the redirect (something your code does not show).

comments powered by Disqus