1
votes

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.

1
What route are you trying? And, does it have a matching file in your public directory? express.static() will only handle things if it finds a matching file. I don't know what your http -> https part of your question is about because you show no code to do that anywhere. - jfriend00
public is a folder which my webpack generated. I'm sure that it matches totally. I need to do something in app.get callback function ex: redirect http -> https. But the code inside that get function never runs. why..? - KevinHu
As I already said, if express.static() matches the route, then it will handle it and no request handlers that come after it will see the request. If you want something to run before the express.static() line, then perhaps you want an app.use() middleware handler BEFORE the express.static() line. You don't show any code that has anything to do with https so I still have no idea what that is about. - jfriend00
ok, I see.. I need to add "app.use()" middleware before express.static() , this middleware can redirect http to https.. right !? - KevinHu

1 Answers

1
votes

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).