hi I try to get host name in node express js -
i use:
var express = require('express'),
app = express();
var port = process.env.PORT || 3000;
app.use(function(req,res,next){
if (req.hostname == "domain1") {
app.get('/', function(req,res){
res.send('Domain1 is active');
}) else if (req.hostname == "domain2") {
app.get('/', function(req,res){
res.send('Doamin2 is active');
});
}
}
next();
});
app.listen(port);
but its works correct only on the first host - if i change host - I have first result
any advice ?
Related
I did read all the other topics but none of the solutions solved my problem.
I write npm start and the server is working as it should but app-root does not it seems like it does not load the client (Angular 2 app).
I just get an empty html page with:
Loading...
(look at my html file down the page)
any idea what can cause it - or any suggested solution ?
Thank you.
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose')
//Set up default mongoose connection
var mongoDB = 'mongodb://localhost/beatblocks';
// Get Mongoose to use the global promise library
mongoose.Promise = global.Promise;
mongoose.connect(mongoDB, function(err) {
if (err){
console.log("error connecting to db...")
}
console.log("connected to database...");
});
// Load Songs Model
require('./models/songs');
const songs = mongoose.model('songs');
// Load Locations Model
require('./models/locations');
const locations = mongoose.model('locations');
// Load users Model
require('./models/users');
const users = mongoose.model('users');
var routeIndex = require('./routes/index');
var routeSongs = require('./routes/songs');
var routeUsers = require('./routes/users');
//var routeLocations = require('./routes/locations');
var app = express();
var router = express.Router();
// Set Static Folder
app.use(express.static(path.join(__dirname, 'views')));
app.use(express.static(path.join(__dirname, '/client/dist')));
app.use(express.static(path.join(__dirname, 'client/src')));
//View Engine
app.engine('ejs', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/', routeIndex);
app.use('/songs', routeSongs);
app.use('/users', routeUsers);
//app.use('/locations', routeLocations);
module.exports = app;
www.js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('beatblocksweb:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
app.listen(port, function(){
console.log('Server started on port '+port);
});
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
my index.html :
<html>
<head>
<title>Beat Blocks</title>
</head>
<body>
<app-root>Loading...</app-root>
<app-header></app-header>
</body>
</html>
my project :
I have the below code for a file server and I would like to use and html page to show an index of the files that are available for download in the static folder "public1"
I currently can serve an html page if the user explicitly requests it but I can't make it automatically serve the html page. The commented out code is my attempt at serving the html page named "hello" by default. It doesn't work...
How can I make the html page display (by default) to the user that navigates to the ip address in a browser?
How can I make the html file show an index of files in the static folder?
So for this two part question, does anyone know how to do this? Can you point me in the right direction.
var express = require('express');
var server = express();
var port = 10001;
//server.get(__dirname + 'public1', function(req, res) {
// res.send('Hello.html');
//});
server.use(express.static(__dirname + '/public1'));
server.listen(port, function() {
console.log('server listening on port ' + port);
});
The easiest way to do this is by using the serve-index and serve-static middleware that is available for express. The below example code works, just swap out the process.cwd() for whatever directory you'd like to serve.
const express = require('express');
const serveIndex = require('serve-index');
const serveStatic = require('serve-static');
const path = require('path');
const server = express();
const port = process.env.PORT || 3000;
function setHeaders(res, filepath) {
res.setHeader('Content-Disposition', 'attachment; filename=' + path.basename(filepath));
}
const dirToServe = process.cwd();
server.use('/', serveIndex(dirToServe, {icons: true}));
server.use('/', serveStatic(dirToServe, {setHeaders: setHeaders}));
server.listen(port, () => {
console.log('listening on port ' + port);
});
Scenario
I have a simple NodeJS server using the Express framework. I have some ReactJS pages that I need to serve. No Isomorphic for now.
Before serving, I want to check if the user has a particular cookie and then based on that I want to create a new cookie.
What I tried
Here is the code for my server.js file.
var express = require("express");
var app = express();
var Cookies = require("cookies");
app.use(function(req, res){
var cookies = new Cookies( req, res);
var userCookie = cookies.get("sso");
var isLoggedIn = cookies.get("isLoggedIn");
if(userCookie !== undefined && isLoggedIn === false){
cookies.set("isLoggedIn", true);
}
});
app.use(express.static(__dirname + '/build'));
var port = process.env.PORT || 8080;
app.listen(port, function() {
console.log("Listening on " + port);
});
So I am using express.static for serving static files from my build folder.
I tried moving the app.use(express.static(__dirname + '/build')); line above the previous app.use, but then the code never enters the cookies section.
I tried this simple thing. Even this didn't worked. I can see log hello, but the website isn't working.
var express = require("express");
var app = express();
app.use(function(req, res){
console.log("hello");
});
app.use(express.static(__dirname + '/build'));
var port = process.env.PORT || 8080;
app.listen(port, function() {
console.log("Listening on " + port);
});
There's a problem with your use of cookies. You're checking if isLoggedIn, the cookie value, === false, a boolean value. But cookies are always strings, so the comparison will always be false and you'll never set isLoggedIn to "true".
If your update your code to treat the values as strings it might work. Try something like this:
if(userCookie !== undefined && isLoggedIn !== "true"){
cookies.set("isLoggedIn", "true");
}
As jeremy's answer pointed out, I was using the cookies the wrong way. But that wasn't the core problem. If code would have run, express server would have thrown error. The real problem was that i wasn't calling the next middleware in the application’s request-response cycle. According to the docs
Middleware is a function with access to the request object (req), the
response object (res), and the next middleware in the application’s
request-response cycle, commonly denoted by a variable named next.
I wasn't calling the next.
So the updated running code is:
var express = require("express");
var app = express();
var Cookies = require("cookies");
app.use(function(req, res, next){
var cookies = new Cookies( req, res);
var userCookie = cookies.get("sso");
var isLoggedIn = cookies.get("isLoggedIn");
if(userCookie !== undefined && isLoggedIn !== "true"){
cookies.set("isLoggedIn", "true",{ httpOnly: false } );
}
next();
});
app.use(express.static(__dirname + '/build'));
var port = process.env.PORT || 8142;
app.listen(port, function() {
console.log("Listening on " + port);
});
All requests are showing GET / 404 8.128 ms-13 in console.
I have posted the code below, there is no error in the code. I can run other NodeJS applications. But this is showing 404 in console. It is not even showing the fav icon. It worked once showing Cannot GET / error and the fav icon was visible at that time.
'use strict';
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');
var logger = require('morgan');
var port = process.env.PORT || 8001;
var four0four = require('./utils/404')();
var environment = process.env.NODE_ENV;
app.use(favicon(__dirname + '/favicon.ico'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(logger('dev'));
app.use('/api', require('./routes'));
console.log('About to crank up node');
console.log('PORT=' + port);
console.log('NODE_ENV=' + environment);
switch (environment){
default:
console.log('** DEV **');
app.use(express.static('./src/client/'));
app.use(express.static('./'));
app.use(express.static('./tmp'));
app.use('/app/*', function(req, res, next) {
four0four.send404(req, res);
});
app.use('/*', express.static('./src/client/index.html'));
break;
}
app.listen(port, function() {
console.log('Express server listening on port ' + port);
console.log('env = ' + app.get('env') +
'\n__dirname = ' + __dirname +
'\nprocess.cwd = ' + process.cwd());
});
According to http://expressjs.com/starter/static-files.html I think that your route here app.use('/*', express.static('./src/client/index.html')); will use ./src/client/index.html as the base path and append whatever you provide to find a file. For example
/some-file will look for ./src/client/index.html/some-file which is obviously not existed
In case you want to understand it more, the static middleware use https://github.com/pillarjs/send internally to stream file
So you can do this
app.use('/*', express.static('./src/client'));
It will, by default, set / to src/client/index.html, you can change that behaviour by setting index option as specified here https://github.com/expressjs/serve-static
If you want to redirect /* to ./src/client/index.html do this
// first set the static middleware
app.use('/public', express.static('./src/client'));
// then use redirect
app.get('/*', function(req, res, next){
res.redirect('/public/index.html');
});
This setup will redirect everything to public/index.html. If you want to add APIs or other routes, put it before the app.get('/*')
I'm trying to create a cluster server with socket.io and express.js I'm following various tutorials on the internet as well on youtube.
What I have at the moment is this code in my app.js:
var cluster = require('cluster');
if (cluster.isMaster) {
var cpuCount = require('os').cpus().length;
var workers = [];
for (var i = 0; i < cpuCount; i++) {
workers[i] = cluster.fork();
}
cluster.on('exit', function (worker){
for (var i = 0; i < workers.length; i++) {
if (worker.process.pid === workers[i].process.pid) {
workers.splice(i, 1);
}
}
for (var i = 0; i < cpuCount - workers.length; i++) {
workers.push(cluster.fork());
}
});
} else {
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
var server = http.createServer(app);
var io = require('socket.io').listen(app.get('port'));
}
When I go to http://localhost:3000/ I get the response:
Welcome to socket.io.
In my previous test scripts I didnt have this issue and my jade templates were being rendered fine. Could someone explain why is this happenning?
Furthermore in my routes directory I have the script: index.js with this code:
/*
* GET home page.
*/
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
Finally in my views folder I have layout.jade with:
doctype 5
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content
and index.jade with:
extends layout
block content
h1= title
p Welcome to #{title}
It seems that the problem was in the final lines of app.js
this fixes the issue:
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(app.get('port'));
Sorry for any inconvenience.