Deploying ReactJS production build in Express as HTTPS - node.js

So I am successful when deploying my React app to production server. I am using Express for deploying. Here is my code.
const express = require('express')
const path = require('path')
const port = process.env.PORT || 80
const app = express()
app.use(express.static(__dirname + '/build'))
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, 'build', 'index.html'))
})
app.listen(port)
I would use CertBot for SSL certs and deploy this as HTTPS server. I really don't know how to approach this problem.

Let's say for example the CertBot generated the SSL certificate and SSL certificate key to the following locations:
/etc/letsencrypt/live/example.org/fullchain.pem
/etc/letsencrypt/live/example.org/privkey.pem
After you have generated your certificate and key, you'll need to utilize the https module directly.
You'll first need to export your Express app:
const express = require('express')
const path = require('path')
const port = process.env.PORT || 80
const app = express()
app.use(express.static(__dirname + '/build'))
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, 'build', 'index.html'))
})
module.export = app
Then simply import your Express app and hook it up with the https module:
const https = require('https');
const fs = require('fs');
const app = require('./app.js');
const server = https.createServer({
key: fs.readFileSync('/etc/letsencrypt/live/example.org/fullchain.pem', 'utf8'),
cert: fs.readFileSync('/etc/letsencrypt/live/example.org/privkey.pem', 'utf8')
}, app);
server.listen(3000);
Note this essentially what ./bin/www does for you except I've adapted it to use https instead of http module.
See What does "./bin/www" do in Express 4.x?

Related

find the error while deploying the node.js app to server

I found the error while deploying the node app on the server. the index.js file code
const connectToDb = require("./DBconfig");
const express = require('express')
const router = express.Router();
var cors = require('cors');
connectToDb();
const app = express();
const port = process.env.PORT | 5000;
app.use(cors());
app.use(express.json());
connectToDb();
app.use( '/api/user' ,require('./routes/user') );
app.use( '/api/post' ,require('./routes/post') );
app.get('/', (req, res) => {
res.send('The site is start now')
})
if(process.env.NODE_ENV === "production"){
app.use(express.static("client/build"));
const path = require("path");
app.get("*",(req,res)=>{
res.sendFile(path.resolve(__dirname,'client','build','index.html'))
})
}
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
when I deploy the app and install the node in the server like how I install the node in server I attached the picture in which I show the installation of the node. and above I add the index.js code. It works properly in the local machine but if I hit the URL of backend backendURL it show the service unavailable error message kindly give me the solution to solve this problem.

Node app is not reachable on EC2 insrance

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);
});

Self host Bitbucket with SSL using Express

I can get bitbucket to run at localhost:7990 just fine however I wanted to secure it with a SSL and also remove the port from the address. When I attempt to do this with the code below and my node server I just simply get the 'CANNOT GET /' error if I goto https://example.com. Even though the bitbucket app is running.
// Dependencies
const fs = require('fs');
const path = require('path');
const http = require('http');
const https = require('https');
const express = require('express');
const express_force_ssl = require('express-force-ssl');
const app = express();
// Certificate
const privateKey = fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem', 'utf8');
const certificate = fs.readFileSync('/etc/letsencrypt/live/example.com/fullchain.pem', 'utf8');
const ca = fs.readFileSync('/etc/letsencrypt/live/example.com/chain.pem', 'utf8');
const credentials = {
key: privateKey,
cert: certificate,
ca: ca
};
app.use(express_force_ssl);
// Load main application
app.use(express.static(path.join(__dirname, '../../var/www/bitbucket/')));
// Starting both http & https servers
const httpServer = http.createServer(app);
const httpsServer = https.createServer(credentials, app);
httpServer.listen(80, (req,res) => {
console.log('HTTPS Server running on port 80');
});
httpsServer.listen(443, (req, res) => {
console.log('HTTPS Server running on port 443');
});

"refused to connect" with https and let-encyrpt

I've successfully created the SSL certificate and the key for my website via letsencrypt.org . I uploaded them in a folder on the server. I get no errors when I start the server.
But when I try to load the website in the browser using https://, I get the "refused to connect" error.
Here is the code I am using to create the https server:
'use strict';
const express = require('express');
const fs = require('fs');
const http= require('http');
const https= require('https');
const path = require('path');
const PRIVATEKEY_PATH = path.join(__dirname, '../ssl/server.key');
const CERTIFICATE_PATH = path.join(__dirname, '../ssl/server.crt');
var privateKey = fs.readFileSync(PRIVATEKEY_PATH, 'utf8');
var certificate = fs.readFileSync(CERTIFICATE_PATH, 'utf8');
var credentials = {key: privateKey, cert: certificate};
// Constants
const PORT = process.env.PORT || 8080;
const HOST = '0.0.0.0';
const CLIENT_BUILD_PATH = path.join(__dirname, '../../300meter.ch/build');
// App
const app = express();
// Static files
app.use(express.static(CLIENT_BUILD_PATH));
//ssh
var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
// All remaining requests return the React app, so it can handle routing.
app.get('*', function(request, response) {
response.sendFile(path.join(CLIENT_BUILD_PATH, 'index.html'));
});
httpServer.listen(PORT, HOST);
httpsServer.listen(8443, HOST);
If somebody could help me, that would be awesome. Thanks!
When you specify https://example.com, the client connects to port 443. You do not have your SSL server running on port 443. Your server is running on port 8443.
You will need to specify https://example.com:8443/ in the URL.

openshift express app serving static files

Noob here. I'm trying to build an api server on Openshift using express. I also want to be able to serve static files from the /static folder. The problem is, I can't figure out how to set it up on Openshift. I've tried everything I can think of.
I have 2 server files, the app setup which calls a router.js file for the routes.
app.js
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const env = process.env;
const app = express();
const router = require('./router');
const mongoose = require('mongoose');
const cors = require('cors');
// DB Setup
// default to a 'localhost' configuration:
var connection_string = '127.0.0.1:27017/api:api';
// if OPENSHIFT env variables are present, use the available connection info:
if(env.OPENSHIFT_MONGODB_DB_PASSWORD){
connection_string = env.OPENSHIFT_MONGODB_DB_USERNAME + ":" +
env.OPENSHIFT_MONGODB_DB_PASSWORD + "#" +
env.OPENSHIFT_MONGODB_DB_HOST + ':' +
env.OPENSHIFT_MONGODB_DB_PORT + '/' +
env.OPENSHIFT_APP_NAME;
}
mongoose.connect('mongodb://' + connection_string);
// App Setup
app.use(morgan('combined')); //logging middleware
app.use(cors()); // allow cross origin requests
app.use(bodyParser.json({ type: '*/*'})); //read requests as json
-----> do I need to put something here ????
router(app);
// Server Setup
const port = env.NODE_PORT || 3090;
const ip = env.NODE_IP || 'localhost';
const server = http.createServer(app);
server.listen(port, ip);
console.log('Server listening on: ', port);
router.js
const Authentication = require('./controllers/authentication');
const passportService = require('./services/passport');
const passport = require('passport');
const requireAuth = passport.authenticate('jwt', { session: false});
const requireSignin = passport.authenticate('local', { session: false});
module.exports = function(app) {
app.post('/signup', Authentication.signup);
app.post('/signin', requireSignin, Authentication.signin);
app.get('/health', function (req, res, next ) {
res.writeHead(200);
res.end();
});
----> and/or something here?
}
Everything works except serving static files. Not sure if I need to put something in the app.js file as middleware, in the router file or both. Also not sure if I need to use Openshift environment variables? Can someone nudge me in the right direction?
In express you can serve static files by adding the following to your app.js using express.static()
var path = require('path');
// put this before all of your routes
app.use(express.static(path.join(__dirname, 'static')));

Resources