node.js - 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 中匹配子域时,它不会向前面发送任何内容......那我可以在这里做什么?
解决方案
尝试删除 response.end()。由于 .sendFile() 接受回调,它很可能是一个异步函数,这意味着在 .sendFile() 之后调用 .end() 很可能会导致空白响应。
推荐阅读
- javascript - 不工作的 javascript 代码 - 某种缓存问题?
- javascript - 当它们位于不同的组件中时,如何堆叠两个容器?
- node.js - 模拟 Intl.NumberFormat 使 Jest Test 独立于当前文化
- python - 回文与对称以及如何处理 2 个单词字符
- sockets - 用于在以太网帧上添加自定义协议的以太网类型
- json - Jq 处理空字符串并用默认值替换它们
- python - mysql插入了第一个值,但它不想插入下一个值 - python
- python - Python从秒和纳秒生成时间戳
- clickhouse - Clickhouse:删除重复数据
- windows - 有没有办法在没有 Windows 10 控制面板的情况下为特定网络适配器禁用 IPv6