2018-11-14
總結: http-proxy-middleware 轉發 post 請求 有問題,沒找到問題所在,換 express-http-proxy 代理。
前后端獨立開發,靜態文件、模板等 前端express服務提供。
后端負責接口。
前端開發 轉發 ajax 到 測試服務器或者開發服務器。
首先 http-proxy-middleware 中間件轉發:
server.js
1 const express = require('express'); 2 const timeout = require('connect-timeout'); 3 const proxy = require('http-proxy-middleware'); 4 5 const app = express(); 6 // 這里從環境變量讀取配置,方便命令行啟動 7 // HOST 指目標地址 8 // PORT 服務端口 9 const { HOST = 'http://xx.xx.xx.xx:8081', PORT = '9090' } = process.env; 10 11 // 超時時間 12 const TIME_OUT = 3000 * 1e3; 13 14 // 設置端口 15 app.set('port', PORT); 16 17 18 設置超時 返回超時響應 19 app.use(timeout(TIME_OUT)); 20 app.use((req, res, next) => { 21 if (!req.timedout) next(); 22 }); 23 24 // 靜態頁面 25 // 這里一般設置你的靜態資源路徑 26 app.use('/', express.static('static')); 27 28 // 反向代理(這里把需要進行反代的路徑配置到這里即可) 29 let opts = { 30 target: HOST , 31 changeOrigin: true, 32 } 33 app.use(proxy('/api', opts)); 34 app.use(proxy('/fmcp/api', opts)); 35 app.use(proxy('/bill-template/api', opts)); 36 app.use(proxy('/metadata-service', opts)); 37 38 39 // 監聽端口 40 app.listen(app.get('port'), () => { 41 console.log(`server running @${app.get('port')}`); 42 });
這個http-proxy-middleware 轉發get請求沒問題,測試post接口的時候503超時,想着是post數據的問題解析的問題,於是引入了body-parser,也沒搞定,不知道什么原因。
換了 express-http-proxy 代理試了下。用法上有些不同。
const express = require('express');
const timeout = require('connect-timeout');
// 換代理中間件
const proxy = require('express-http-proxy');
const app = express();
// 這里從環境變量讀取配置,方便命令行啟動
// HOST 指目標地址
// PORT 服務端口
const { HOST = 'http://xx.xx.xx.xx:8081', PORT = '9090' } = process.env;
// 超時時間
const TIME_OUT = 3000 * 1e3;
// 設置端口
app.set('port', PORT);
// 設置超時 返回超時響應
// app.use(timeout(TIME_OUT));
app.use((req, res, next) => {
if (!req.timedout) next();
});
// 靜態頁面
// 這里一般設置你的靜態資源路徑
app.use('/', express.static('static'));
// 反向代理(這里把需要進行反代的路徑配置到這里即可)
let opts = {
preserveHostHdr: true,
reqAsBuffer: true,
//轉發之前觸發該方法
proxyReqPathResolver: function(req, res) {
//這個代理會把匹配到的url(下面的 ‘/api’等)去掉,轉發過去直接404,這里手動加回來,
req.url = req.baseUrl+req.url;
console.log(1,req)
return require('url').parse(req.url).path;
},
}
app.use('/api', proxy(HOST,opts));
app.use('/fmcp/api', proxy(HOST,opts));
app.use('/bill-template/api', proxy(HOST,opts));
// 監聽端口
app.listen(app.get('port'), () => {
console.log(`server running @${app.get('port')}`);
});
這個 get post 都沒問題。
總結: http-proxy-middleware 轉發 post 請求 有問題,沒找到問題所在,換 express-http-proxy 代理。
