Vhost + express why doesn't work? - node.js

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

Related

Why is my heroku app loading resources too long even after using gzip compression?

I have a MEAN stack app hosted in Heroku. In my Express server, I use gzip (via compression middleware).
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const adminpassport = require('passport');
const mongoose = require('mongoose');
const config = require('./config/database');
// Connect to DB
mongoose.connect(config.database);
mongoose.connection.on('connected',()=>{
console.log('Connected to database '+config.database);
});
mongoose.connection.on('error',(err)=>{
console.log('DB Error '+err);
});
const compression = require('compression');
const app = express();
// Static Folder
app.use(express.static(path.join(__dirname, 'public')));
app.use(compression());
// Body Parser Middleware
app.use(bodyParser.json());
...
app.use(function(req, res) {
res.sendFile(path.join(__dirname, '/public', 'index.html'));
});
// Index Route
app.get('/', (req, res)=>{
res.send('Invalid enpoint');
});
app.listen(port, ()=>{
console.log("Server started on port "+port);
});
The problem is that the Angular main.js file (that is orginally 3.2mb, compressed to 575kb) is still seemingly being download as if it's still the uncompressed size. Here's an image of the load times:
I know my internet connection is fine (around 20mbps). Is there anything I'm missing? Is there something wrong in my implementation of gzip? Or even my Heroku dyno? This app is currently on the hobby dyno. I did change it to the professional one but didnt notice any difference.
I'm not sure what is your environment, but you can try this, is completely functional for me.
// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const compression = require('compression');
const runApp = async() => {
const app = express();
app.use(compression({
filter: function (req, res) {
return (/json|text|javascript|css|font|svg/).test(res.getHeader('Content-Type'));
},
level: 9
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.get('*', (req, res) => {
console.log('Front end called');
res.sendFile(path.join(__dirname, 'public/index.html'));
});
/**
* Get port from environment and store in Express.
*/
const port = process.env.PORT || '8081';
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}`));
};
runApp();

Having two seperate routes in node/express, where one accepts all the requests

In my node/express app, I have the following app.js file with the following routing
const express = require('express');
const path = require('path');
const logger = require('./middleware/logger');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
app.use(cors());
app.use(express.static(path.join(__dirname,'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.json());
app.use(express.urlencoded({extended:false}));
app.use('/wsserver', require('./routes/wsroutes'));
app.use('/', require('./routes/company'));
const port = process.env.PORT || 3000;
app.listen(port, ()=>{
console.log('server runs on port ', port);
});
Every request that goes to http://localhost:8080/wsserver, is handeld by wsroutes. I am planning to setup a websockets server in there, but for now contains
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('ws');
})
module.exports = router;
The / handles all the other requests and its handled by the company that contains
router.get('/',(req, res)=>{ ....
router.get('/:companyName/:id?/:employ?',(req, res)=>{ ...
etc
As you can guess, the problem is that when I go to http://localhost:8080/wsserver, is handled by the / route and the company route. I get the interface and the message no company named wsserver , because the wsserver becomes an argument in the router.get('/:companyName/:id?/:employ?' route.
How can I still have both routes, not change the / one and have them both work correctly? I tried to change positions in the routes like so
app.use('/', require('./routes/company'));
app.use('/wsserver', require('./routes/wsroutes'));
ans still nothing.
What else can I do ?
Thanks

Node Js saving to a txt file not working

I have a server running on Node Js. What I'm doing is whenever the users submit something to save their input to a text file. When I run my server as a localhost it works and saves the input to the file. Whenever I run it on the real published server it doesn't. Is there a way to accomplish it on the real server without a database?
My code:
var fs = require('fs');
const log=require('simple-node-logger').createSimpleLogger();
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var port = process.env.PORT || 8081;
app.use(express.static(__dirname + '/server'));
app.use(express.static(__dirname + '/public'));
app.use('/images', express.static(__dirname +'/images'));
app.get('/', function(req, res){
res.sendFile('main.html');
});
app.listen(port, function(){
console.log('Server is running on port:' + port);
});
app.post('/submit', function(req, res){
var data = fs.writeFileSync('fileSync', req.body.rank, 'utf8');
return res.sendFile('success.html');
});
Thank you in advance!

node Cannot POST /api/register

I'm not sure why I am getting the cannot POST error. I am passing the correct routes. The server is listening on a port.
index.js
const router = require('./router');
var app = express()
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var server = app.listen(process.env.PORT || 8080, function() {
var port = server.address().port;
console.log("App now running on port", port);
});
router(app);
router.js
const Authentication = require('./authentication');
const express = require('express');
const passport = require('passport');
const requireAuth = passport.authenticate('jwt', { session: false });
const requireLogin = passport.authenticate('local', { session: false });
module.exports = function(app) {
const apiRoutes = express.Router();
const authRoutes = express.Router();
apiRoutes.use('/auth', authRoutes);
authRoutes.post('/login', requireLogin, Authentication.login);
authRoutes.post('/register', Authentication.register);
app.use('/api', apiRoutes);
};
You're trying to access /api/register, but look at the way you've registered your routers:
apiRoutes.use('/auth', authRoutes);
authRoutes.post('/login', requireLogin, Authentication.login);
authRoutes.post('/register', Authentication.register);
app.use('/api', apiRoutes);
You've made authRoutes a child of apiRoutes, so /register is being served at api/auth/register.
Easy mistake to make when you've got several routers all linked up to each other :)

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