第一种:nginx配置
conf主要的配置代码:
http { # nginx负载均衡配置 upstream dynamic_balance { #ip_hash; server 192.168.100.123: 8081; } # 省略其他 server { listen 80; server_name localhost; #访问工程路径 root website; index index.html index.htm; #转发把原http请求的Header中的Host字段也放到转发的请求 proxy_set_header Host $host; #获取用户真实IP proxy_set_header X - real - ip $remote_addr; proxy_set_header X - Forwarded - For $proxy_add_x_forwarded_for; #接口转发 location /base/ { proxy_pass http: //dynamic_balance; } #启用history模式( 什么请求都只返回index.html) location / { try_files $uri $uri / /index.html; } } }
第二种:原生node.js
const http = require('http'); const fs = require('fs'); const path = require('path'); const httpProxy = require('http-proxy'); const childProcess = require('child_process'); // 可自动打开浏览器 const filepath = path.resolve(__dirname,'../'); const proxy = httpProxy.createProxyServer(); // 创建代理服务器 const {proxyTable = [],port = 8080} = require('./index.js'); http.createServer(function(req,res){ fs.readFile(filepath + req.url,function(err,data) { proxyTable.forEach((item) => { if(req.url.indexOf(item.api) !== -1) { // 匹配上接口代理 proxy.web(req,res,{target: item.target}); proxy.on('error',function(e) { // 代理失败处理 console.log(e); }) } else { if(err) { fs.readFile(filepath + '/index.html', 'utf-8',(err,data) => { res.write(data); res.end() }) } else { res.write(data); res.end(); } } }) }) }).listen(port,() => { console.log('服务启动了'); }); childProcess.exec(`start http://localhost:${port}/`);
这儿用到了接口代理,需要安装http-proxy:npm i http-proxy -D。
其中引入的index.js代码如下:
module.exports = { port: 8081, host: 'localhost', proxyTable: [{ api: '/webgate', target: 'http://192.168.100.112:8080/' }] }
第三种:基于 Node.js 的 Express的connect-history-api-fallback 中间件
const history = require('connect-history-api-fallback'); const express = require('express'); const path = require('path'); const { createProxyMiddleware } = require('http-proxy-middleware'); const app = express(); const childProcess = require('child_process'); const {proxyTable = [],port = 8080,host = 'localhost'} = require('./index.js'); const pathname = path.resolve(__dirname, '../'); app.use('/',history({ index: `/console.html`, verbose: true })); app.use('/',express.static(`${pathname}`)); // 设置静态资源访问路径 proxyTable.forEach((item) => { app.use(createProxyMiddleware(item.api,{ target: item.target, changeOrigin: true, ws: true })); }) app.listen(port,() => { console.log(`listen:${port}`); }) childProcess.exec(`start http://${host}:${port}`)
其中引入了的index.js跟第二种代码一样。
参考地址:《HTML5 History 模式》