首页 > 解决方案 > express.static() 和 sendFile() 问题...用nodejs创建动态主机

问题描述

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

但在此之前,我处理 http 请求,我检查 url 和主机以查看它是否正确。

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

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

用户应访问本网站并收到 Angular 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 中匹配子域时,它不会向前面发送任何内容......那我可以在这里做什么?

标签: node.jsexpress

解决方案


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


推荐阅读