第一次 使用markdown编辑器,主要熟悉一下markdown的语法,发一段最近学习的server.js,方便将来回头看看自己写的代码有多丑。
server.js采用express生成,中间采用compression压缩,采用http-proxy反向代理,采用log4js在console输出日志。代码基本采用的就是将教材中的代码堆叠过来的,各位道友看看就算了。
'use strict';
var express = require('express');
var path = require('path');
var compression = require('compression');
var httpProxy = require('http-proxy');
// var targetHost = process.env.PROXY_HOST || '192.168.1.1:8080';
var targetHost = process.env.PROXY_HOST || 'www.falseweb.cn';
var defaultTargetHostPort = process.env.PROXY_PORT || '8080';
var app = express();
var proxy = httpProxy.createProxyServer();// 该方法用来做反向代理
var publicDir = path.normalize(path.join(__dirname, '..', ''));
app.use(compression()); //app压缩
var log4js = require('log4js');
log4js.configure({
appenders: [
{
type: 'console',
"category": "logInfo"
}
],
replaceConsole: true
});
var logger = log4js.getLogger('logInfo');
logger.setLevel(log4js.levels.INFO);
app.use(log4js.connectLogger(logger, {level:log4js.levels.INFO}));
// app.use(express.static(publicDir, {'redirect': false}));
// express.static() 用来托管静态文件 只有进行托管 才可以通过url路径访问
app.use('/app', express.static(path.join(__dirname, '..', 'app')));
app.use('/assets', express.static(path.join(__dirname, '..', 'assets')));
app.use('/app/views', express.static(path.join(__dirname, '..', 'app', 'views')));
app.use('/vendor', express.static(path.join(__dirname, '..', 'vendor')));
app.use('/src', express.static(path.join(__dirname, '..', 'src')));
//app.get 使用回调函数处理路由
app.get('/demoui', function(req, res){
res.sendfile(path.join(__dirname, '..', 'src/demoui/index.html'));
});
app.get('/pc', remoteRequest);
app.get('/index2',remoteRequest);
app.get('/', remoteRequest);
// app.get('/',function(req,res){
// res.sendfile(path.join(__dirname, '..', 'index.html'));
// });
app.get("/logout", remoteRequest);
//app.get("/pc", localTestRequest);
function localTestRequest(targetHost, req, res){ //本地测试请求,没有调用
targetHost += [':', defaultTargetHostPort].join("");
req.headers.host = targetHost;
req.headers.origin = 'http://' + targetHost;
proxy.web(req, res, {target: req.headers.origin + '/'});
}
function remoteRequest(req, res){ //远程请求
req.headers.host = targetHost;
req.headers.origin = 'http://' + targetHost;
proxy.web(req, res, {target: req.headers.origin + '/'});
}
//app.all("/ajax/*", remoteRequest);
app.all("/*", remoteRequest);
app.listen(8081, '0.0.0.0', function () {
console.log("server started at http://localhost:8081");
});