expressjs / vhost

virtual domain hosting

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

req.vhost is undefined

mrrovot opened this issue · comments

commented

This is my main code, but I get req.vhost is undefined, any idea what can cause it?

app.use(function(req, res, next){
console.log(req.vhost)
  var username = req.vhost[0] // username is the "*"
  console.log(username)
 
  // pretend request was for /{username}/* for file serving
  req.originalUrl = req.url;
  console.log('req '+ req.originalUrl)
  req.url = '/' + username + req.url
  console.log(req.url)


  next()
})

app.use(vhost('*.myapp.local', indexRouter))

if I delete the console logs in the middleware the right route is rendered, but it is important to have access to the req.vhost[0] to render dynamic data based on the subdomain the user is typing

Hi @mrrovot , the req.vhost property is not populated until the request actually passes though this middleware. In your example, you are accessing req.vhost before this middleware is ever invoked. In addition, the req.vhost property is only available within the defined handler, which in your case is the indexRouter.

I hope that helps.

commented

Got it ,thanks!

Now I do get the req.vhost but can't access req.vhost[0]

req.vhost prints out

{ '0': 'v1',
  host: 'v1.myapp.local:3000',
  hostname: 'v1.myapp.local',
  length: 1 }

but when I try to get req.vhost[0] it gives me undefined? what could cause that, if I paste the object in a browser console to test and then try to access the [0] index/property it does return 'v1'

I'm not sure, I've never seen that behavior before. It's possible there is a bug here or in Node.js itself. Is it possible to provide a replication I can reproduce and poke at? Because I don't have any idea why req.vhost[0] would return undefined if it looks like what you pasted there.

  1. Version of Node.js
  2. Version of this module
  3. Complete code that I can copy and paste and run as-is without modification. You'd be surprised at what things in the code may affect something else, so having some complete code I don't have to modify to reproduce helps.
  4. Instructions on how to reproduce (really, just what call to make the to given code).

Thanks!

commented

I am on node v10.13.0 and vhost: ^3.0.2

the code is so far a almost intact express js from the generator, it happens when I go to v1.myapp.local:3000 route, it does return the req.vhost but can't get the [0]

app.js


var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var vhost = require('vhost')
// var serveStatic = require('serve-static')

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());



app.use(express.static(path.join(__dirname, 'public')));
app.use('/site', express.static(path.join(__dirname, 'sites')));
// app.use(serveStatic(path.join(__dirname, 'sites')))


app.use(function(req, res, next){
  // var username = req.vhost[0] // username is the "*"
  // console.log(username)
 
  // // pretend request was for /{username}/* for file serving
  // req.originalUrl = req.url;
  // console.log('req '+ req.originalUrl)
  // req.url = '/' + username + req.url
  // console.log(req.url)

   res.locals.userTest = "jason"
 

  next()
})



app.use(vhost('*.myapp.local', indexRouter))

// app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

router/index.js


var express = require('express');
var router = express.Router();


router.get('/',function(req,res,next){
  console.log(req.vhost)
  console.log(res.locals)
	  var options = {
    root: __dirname + '/../sites/',
    dotfiles: 'deny',
    headers: {
        'x-timestamp': Date.now(),
        'x-sent': true
    }
  };

  var fileName = req.params.name;
  res.sendFile('index.html', options, function (err) {
    if (err) {
      next(err);
    } else {
      console.log('Sent:', fileName);
    }
  });

});


module.exports = router;


Thanks @mrrovot . I only see you trying to use req.vhost[0] in once place, but that is the wrong place from our earlier conversation. Where are you trying to use it in the code where req.vhost works, but req.vhost[0] does not work? I don't see that anywhere, and not sure were to put it. Ideally if you can post code I can just run as-is to see the issue vs trying to guess where to place certain pieces of code would help.

commented

the req.vhost[0] is commented out, I meant where there is console.log(req.vhost) I couldn't access the[0]but as I was recreating a simple app with the error to send you, it now it works!, probably it was something I mistyped last night

thanks for the help