Giter Site home page Giter Site logo

req.vhost is undefined about vhost HOT 6 CLOSED

expressjs avatar expressjs commented on May 8, 2024
req.vhost is undefined

from vhost.

Comments (6)

dougwilson avatar dougwilson commented on May 8, 2024 2

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.

from vhost.

mrrovot avatar mrrovot commented on May 8, 2024

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'

from vhost.

dougwilson avatar dougwilson commented on May 8, 2024

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!

from vhost.

mrrovot avatar mrrovot commented on May 8, 2024

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;


from vhost.

dougwilson avatar dougwilson commented on May 8, 2024

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.

from vhost.

mrrovot avatar mrrovot commented on May 8, 2024

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

from vhost.

Related Issues (16)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.