localhost:300/localhost:443 redirect to localhost with nodejs

Hello everybody and thanks in advance for your answer.
I have a website which is serve by nodejs and I’m listening on port 300 for http and 443 for https:

const fs = require('fs');
const https = require('https');
const http = require('http');
const app = require('../app');
const env = require(`../environment/${process.env.NODE_ENV}`);

const httpServer = http.createServer((req, res) => {
  res.writeHead(301, { Location: `https://${req.headers.host.split(':')[0] + ':' + env.portHttps}${req.url}` });

const options = {
  key: fs.readFileSync(env.key),
  cert: fs.readFileSync(env.cert),

const httpsServer = https.createServer(options, app).listen(env.portHttps);

This code is from a tutorial and I guess I don’t understand it well because I was expecting to get my site calling localhost:300 or localhost:443 and each time, the request on google chrome redirect to https://localhost/ and I don’t get why.

So it works fine but I’d like to know why the redirection because … Why calling a .listen(port) then ?

PS: I have an angular app launch with a proxy :

    "/": {
        "target": "https://localhost",
        "changeOrigin": true,
        "secure": false

I know the purpose of this proxy, I only wonder why the redirection happen and the tutorial I’ve followed does’t explain that.

>Solution :

You are creating an http server on port 80 and sending back a 301 HTTP Redirect to all requests.
These redirects work by returning status code 301 and an HTTP header Location with where you’d like the browser to go to. So when you visit http://localhost/abc you receive 301, Location: https://localhost/abc and your browser takes you there.

In the dev tools, if you go to the network tab and enable "preserve log" you should see both the redirect and the actual application page load.

const httpServer = http.createServer((req, res) => {
  // 301 is the http status code
  // Location: ... is the header which contains where to go to
  res.writeHead(301, { Location: `https://${req.headers.host.split(':')[0] + ':' + env.portHttps}${req.url}` });

At the bottom of the file you set up the https server which listens on port 443 and serves your application.

Leave a Reply