I am trying to redirect all HTTP traffic to HTTPS using my express server. I am running the server on AWS lightsail Mean stack. I have tried setting auto redirect from HTTP to HTTPS when I set up my SSL on lets-encrypt but that didn't work. I can't set the redirect on apache because I am using ports 80 and 443 with express so I have to disable apache. So I tried to come up with something for the redirection using only express. Below is a code I tried. Basically what I did was listen to all traffic on port 80 and redirect them to HTTPS but this method isn't working too. Is there a way to redirect HTTP to HTTPS using express? Thanks in advance.
'use strict';
const express = require('express')
const http = require('http')
const https = require('https')
const fs = require('fs')
const path = require('path')
const cookie = require('cookie-parser')
const domain = 'mydomain.com'
const app = express()
app.use('/js', express.static(__dirname + '/public/js'))
app.use('/css', express.static(__dirname + '/public/css'))
app.set('view engine', 'ejs')
app.set('views', './views')
app.use(cookie())
app.use(express.json({ limit: '50mb' }));
app.use('/', require('./routes/pages'))
app.use('/api', require('./controllers/auth'))
app.get('*',function(req, res){
res.redirect('https://' + domain + req.path);
});
http.createServer(app).listen(80, function(){
console.log('HTTP listening on port 80');
});
const appSecure = express();
appSecure.use('/js', express.static(__dirname + '/public/js'))
appSecure.use('/css', express.static(__dirname + '/public/css'))
appSecure.set('view engine', 'ejs')
appSecure.set('views', './views')
appSecure.use(cookie())
appSecure.use(express.json({ limit: '50mb' }));
appSecure.use('/', require('./routes/pages'))
appSecure.use('/api', require('./controllers/auth'))
var options = {
key: fs.readFileSync('/home/bitnami/htdocs/letsencrypt/certificates/www.mydomain.com.key'),
cert: fs.readFileSync('/home/bitnami/htdocs/letsencrypt/certificates/www.mydomain.com.crt'),
};
https.createServer(options, appSecure).listen(443, function(){
console.log('HTTPS listening on port 443');
});
All, you need for the http server is this:
const domain = 'mydomain.com';
const app = express();
// redirect every single incoming request to https
app.use(function(req, res) {
res.redirect('https://' + domain + req.originalUrl);
});
app.listen(80);
You don't want all your other route handlers on the http server because what you want to do is just redirect any http:// URL immediately to the https:// version of the URL and you never serve any content from the http URL.
Note, this also uses req.originalUrl in constructing the redirect URL because that will include any query parameters too.
Related
I have deployed simple nodejs application on EC2 instance and modified all inbound rules to made port publicly accessible but even after that I am unable to access application.
below is my app:
server.js
const express = require('express');
const log = require('./logger');
const app = express();
app.get('/',(req,res) => {
res.send("Happy logger");
});
app.listen(2000,() => console.log("App is listening"));
Below is my inbound rules settings
When I am hitting on ec2-3-82-196-99.compute-1.amazonaws.com:2000 url its showing below error.
Someone let me know what I am doing wrong.
From your screenshot, you are accessing HTTPS in Chrome:
https://ec2-3-82-196-99.compute-1.amazonaws.com:2000.
As the commenter suggested, should use HTTP instead (make sure you see the 'Not secure' sign):
http://ec2-3-82-196-99.compute-1.amazonaws.com:2000
I am also having the same problem here.
I tried both HTTP and HTTPS, but no use. The app is working in the localhost (A windows 2022 server).
URLS:
https://ec2-3-110-102-41.ap-south-1.compute.amazonaws.com:8080
http://ec2-3-110-102-41.ap-south-1.compute.amazonaws.com:8080
Security Inbound Rules:
Inbound Rules
NodeJS Code:
const express = require("express");
const cors = require("cors");
const dotenv = require('dotenv')
dotenv.config();
const app = express();
app.use(cors({
origin: "*"
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get("/", (req, res) => {
res.json({ message: "Hello" });
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, '0.0.0.0', () => {
console.log("Server listening on port::::::::::::::::::::::\n", PORT);
});
I try to configure my node.js + express application for creation multiple domain server. This is my code, but unfortunately it's not working. Please explain me, what is wrong in this code?
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const vhost = require('vhost')
const app = express();
app.use(bodyParser.json());
// Port
const port = 8081;
app.use('/', express.static(path.join(__dirname, 'public')));
app.use(vhost('*.localhost:8081', function(req, res, next){
res.send('Ok, its work.');
}));
app.listen(port, function(){
console.log('App is running on port '+ port);
});
I have the following code which is defaulting to use HTTPS, I'm just unclear how to send an index.html file back
var express = require('express'),
path = require('path'),
fs = require('fs'),
app = express(),
staticRoot = __dirname + '/',
httpsRedirect = require('express-https-redirect');
app.set('port', (process.env.PORT || 3001));
app.use('/', httpsRedirect())
app.listen(app.get('port'), function () {
console.log('app running on port', app.get('port'));
});
Any help is greatly appreciated
You can send the html file usually asfollows
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
Note: express-https-redirect middleware redirects non-secure access to HTTPS Only.
I am starting a MEA2N app, and built a small express server running on port 3000.
The angular app runs on port 4200. If I open localhost 3000 I see 'loading...' ergo the app does not run. While if I open localhost 4000 I get 'app working'. Does anybody know how this might happen?
server.js is very standard:
// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
// Get our API routes
const api = require('./server/routes/api');
const app = express();
// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));
// Set our api routes
app.use('/api', api);
// Catch all other routes and return the index file
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, './src/index.html'));
});
/**
* Get port from environment and store in Express.
*/
const port = process.env.PORT || '3000';
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, () => console.log(`API running on localhost:${port}`));
server.js is running in root folder.
angular app is root/src/indxex.html and root/src/app/
If server.js is in root folder and angular app is on root/src/index.html
then
app.use(express.static(path.join(__dirname, 'dist')));
should be
app.use(express.static(path.join(__dirname, '/src')));
I'm learning MEAN stack with 'Getting MEAN with...' book, and problem is older Express version in books than i use.
The first step is to tell our application that we’re adding more routes to look out for,
and when it should use them. We already have a line in app.js to require the server
application routes, which we can simply duplicate and set the path to the API routes
as follows:
var routes = require('./app_server/routes/index');
var routesApi = require('./app_api/routes/index');
Next we need to tell the application when to use the routes. We currently have the following line in app.js telling the application to check the server application routes for
all incoming requests:
app.use('/', routes);
Notice the '/' as the first parameter. This enables us to specify a subset of URL s for
which the routes will apply. For example, we’ll define all of our API routes starting
with /api/ . By adding the line shown in the following code snippet we can tell the application to use the API routes only when the route starts with /api :
app.use('/', routes);
app.use('/api', routesApi);
And there's listing of my app.js file:
var express = require('express')
, others = require('./app_server/routes/others')
, locations = require('./app_server/routes/locations')
, routesApi = require('/app_api/routes/index')
, ;
require('./app_server/models/db')
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/app_server/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
// LOCATION PAGES
app.get('/', locations.homeList);
app.get('/location', locations.locInfo);
app.get('/location/review/new', locations.addReview);
// OTHER PAGES
app.get('/about', others.about);
app.listen(3000, function(){
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
Can someone explain me how to do the same in my Express version ?
In Express 4, this is done using Router Middleware. More info is available on Express Routing here.
A Router is simply a mini express app that you can define middleware and routes on that should all be packaged together, ie /api should all use apiRouter. Here is what apiRouter could look like
apiRouter.js
var express = require('express')
var router = express.Router(); // Create our Router Middleware
// GET / route
router.get('/', function(req, res) {
return res.status(200).send('GET /api received!');
});
// export our router middleware
module.exports = router;
Your main Express app would stay the same, so you would add your router using a require() to import the actual file, and then inject the router with use()
Express Server File
var express = require('express');
var app = express();
var apiRouter = require('../apiRouter');
var port = process.env.PORT || 3000;
app.use('/', apiRouter);
app.listen(port, function() {
console.log('listening on ' + port);
});