第一種: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 模式》
