express.static()和sendFile()问题...使用nodejs创建动态主机

时间:2019-04-29 16:42:09

标签: node.js express

在用nginx配置我的Web服务器之后,我将所有* .example.com重定向到了我的nodejs服务器。

但是,在我处理http请求之前,我检查了网址和主机,看是否正确。

例如,如果用户写了类似what.ever.example.com之类的内容 我将他重定向到主要网站,因为该主机无效。

否则,如果用户写了mydomain.example.com之类的内容

用户应访问该网站并获得有角度的APP。

所以我正在做这样的事情。

  

更新代码

const express = require('express');
const cors = require('cors');
const mongoose = require('./server/database');
const bodyParser = require('body-parser');
const app = express();
var path = require('path');

// Settings
app.set('port', process.env.PORT || 4000)

// Middlewares
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());

// Routes API
app.use('/api/users', require('./server/routes/usuarios.routes'));
app.use('/api/almacenes', require('./server/routes/almacen.routes'))
app.use('/api/updates', require('./server/routes/update.routes'))
app.use('/api/dominios', require('./server/routes/dominios.routes'))

app.get('/', checkHost);
app.get('/', express.static('../nginx/app'));
app.get('/*', checkPath);

function checkHost(req, res, next) {  //With this function what i pretend is check the subdomain that the user send, and if it doesn't exist. redirect it. 
  var domain = req.headers.host
  subDomain = domain.split('.')
  if (subDomain.length == 3) {
    subDomain = subDomain[0].split("-").join(" ");
    let query = { dominio: subDomain }
    var dominiosModel = mongoose.model('dominios');
    dominiosModel.findOne(query).exec((err, response) => {
      if (response != null) {
        if (response.dominio == subDomain) {
          next();
        } else {
          res.writeHead(303, {
            location: 'http://www.example.com/index.html'
          })
          res.end()
        }
      } else {
        res.writeHead(303, {
          location: 'http://www.example.com/index.html'
        })
        res.end()
      }
    })
  } else {
    res.writeHead(303, {
      location: 'http://www.example.com/index.html'
    })
    res.end()
  }
}

function checkPath(req, res, next) { //With this function what i want to do is.. if the user send *.example.com/whatever, i redirect it to *.example.com
  if (req.url !== '/') {
    res.writeHead(303, {
      location: `http://${req.headers.host}`
    })
    res.end()
  } else {
    next()
  }
}



// Starting Server.
app.listen(app.get('port'), () => {
  console.log('Server listening on port', app.get('port'));
});

所有重定向都运行良好,但是当在checkHost中匹配subDomain时,它不会向前发送任何内容...所以我在这里可以做什么?

2 个答案:

答案 0 :(得分:1)

尝试删除response.end()。由于.sendFile()接受回调,因此它很可能是异步函数,这意味着在.sendFile()之后立即调用.end()很有可能会导致响应为空。

答案 1 :(得分:1)

如果未提供root,则sendFile函数需要发送文件的绝对路径。如果提供了root,则可以使用相对路径,但是root本身应该是绝对路径。在此处查看文档:{​​{3}}

您应尝试通过以下方式发送index.html

app.get('*', checkPath, checkHost, function (req, response) {
  response.sendFile('index.html', { root: path.join(__dirname, '../nginx/app') });
}

只要相对于写入此代码的文件的路径../nginx/app/index.html有效,这应该起作用。

此外,根据示例代码(和注释),您可能根本不需要express.static(...)。除非您需要静态提供“其他”文件。

如果需要,则app.use(express.static('../nginx/app'))应该在控制器外部。可能应该在bodyParser之前添加它,但是由于您担心有人可以通过静态中间件访问'index.html',因此可以考虑对中间件进行以下排序:

//existing body parser and cors middlewares

// existing /api/* api middlewares. 

app.use(checkPath);
app.use(checkHost);
app.use(express.static('../nginx/app'));

如果将checkPath中间件稍作修改以重定向到/index.html,则在此设置中可能根本不需要具有'*'路径的中间件。