KevinHu
KevinHu

Reputation: 1031

Code inside get not running after using express.static

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.

Upvotes: 1

Views: 814

Answers (1)

jfriend00
jfriend00

Reputation: 707158

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 https server can process your URLs after the redirect (something your code does not show).

Upvotes: 2

Related Questions