1. 程式人生 > >node express 中介軟體 http-proxy-middleware 和 express-http-proxy 轉發 搞定 post 超時

node express 中介軟體 http-proxy-middleware 和 express-http-proxy 轉發 搞定 post 超時

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://10.10.65.43: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://10.10.65.43: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 代理。