/** * Created by lijunhao on 1/19/17. */var url = require("url");var proxy = require('http-proxy').createProxyServer({});// 自定义路由分发规则,从前向后匹配var rules = [ ['Static', 'http://localhost:8080', /.*\.(js|css|htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma|ico)$/], ['Index', 'http://localhost:8080', /^\/$/], ['Backend', 'http://10.10.1.14:8080', /\/.+/]];var server = require('http').createServer(function(req, res) { // var host = req.headers.host, ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; // console.log("Raw - client ip:" + ip + ", host:" + host + "); var path = url.parse(req.url).pathname; console.log(path); for (var i in rules) { var r = rules[i]; if (r[2].test(path)) { console.log(path + ' -----> ' + r[1]); //这里的target只会替换ip和端口,而不会替换后面的 proxy.web(req, res, {target: r[1]}, function (err) { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end('{"msg": "代理后端异常"}'); }); return; } } res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Welcome to proxy server!');});server.listen(3000);console.log('Proxy server started');
例如:
效果是把后端的接口代理到真实的接口。。静态文件找自己的路径好处,实现前后端分离!!!